package com.lanswon.qzsmk.service.cardManageService.impl;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lanswon.common.card.CardUtil;
import com.lanswon.qzsmk.base.AccountContants;
import com.lanswon.qzsmk.base.AppContants;
import com.lanswon.qzsmk.base.BankFileContants;
import com.lanswon.qzsmk.base.BlackListContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.ListPageUtil;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.dao.AppKindMapper;
import com.lanswon.qzsmk.dao.AppOpenRegMapper;
import com.lanswon.qzsmk.dao.BatchCollectionMapper;
import com.lanswon.qzsmk.dao.BlackListGenMapper;
import com.lanswon.qzsmk.dao.BlackListRcMapper;
import com.lanswon.qzsmk.dao.BusiParamMapper;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.dao.CardBatchMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardManageMapper;
import com.lanswon.qzsmk.dao.CardNoGeneratedMapper;
import com.lanswon.qzsmk.dao.CardNoUseDetailMapper;
import com.lanswon.qzsmk.dao.CardPhysicsTypeMapper;
import com.lanswon.qzsmk.dao.CardProdunctDefinitionMapper;
import com.lanswon.qzsmk.dao.CardTaskMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.CertificateMapper;
import com.lanswon.qzsmk.dao.CooperationCompanyMapper;
import com.lanswon.qzsmk.dao.CorporationMapper;
import com.lanswon.qzsmk.dao.FileStatusMapper;
import com.lanswon.qzsmk.dao.MainAccountPersonalMapper;
import com.lanswon.qzsmk.dao.PersonalMapper;
import com.lanswon.qzsmk.dao.SubaccountPersonalMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.AppKind;
import com.lanswon.qzsmk.model.AppOpenReg;
import com.lanswon.qzsmk.model.BlackListGen;
import com.lanswon.qzsmk.model.BlackListRc;
import com.lanswon.qzsmk.model.Business;
import com.lanswon.qzsmk.model.CardBatch;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CardManage;
import com.lanswon.qzsmk.model.CardNoGenerated;
import com.lanswon.qzsmk.model.CardNoUseDetail;
import com.lanswon.qzsmk.model.CardProdunctDefinition;
import com.lanswon.qzsmk.model.CardTask;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.model.CooperationCompany;
import com.lanswon.qzsmk.model.FileStatus;
import com.lanswon.qzsmk.model.MainAccountPersonal;
import com.lanswon.qzsmk.model.Personal;
import com.lanswon.qzsmk.model.SubaccountPersonal;
import com.lanswon.qzsmk.service.cardManageService.ApplyCardService;
import com.lanswon.qzsmk.service.cardManageService.BanckCardBusinessService;
import com.lanswon.qzsmk.util.CommonUtil;
import com.lanswon.qzsmk.util.CopyBean;
import com.lanswon.qzsmk.util.FileUtil;
import com.lanswon.qzsmk.util.FtpUtil;
import com.lanswon.qzsmk.util.HttpUtil;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.util.ZipUtil;
import com.lanswon.qzsmk.vo.BankLossCancleVo;
import com.lanswon.qzsmk.vo.BankProvideChangeCardVo;
import com.lanswon.qzsmk.vo.BankProvidePersonalVo;
import com.lanswon.qzsmk.vo.CardNoGeneratedVo;
import com.lanswon.qzsmk.vo.ImportBankFileVo;
import com.lanswon.qzsmk.vo.MakeCardFileReturnFileVo;
import com.lanswon.qzsmk.vo.MakeCardInfo;
import com.lanswon.qzsmk.vo.MakeCardQueryResultVo;

import ch.qos.logback.classic.Logger;

@Service
public class BanckCardBusinessServiceImpl implements BanckCardBusinessService {
	
	private static Logger logger = (Logger) LoggerFactory.getLogger(BanckCardBusinessServiceImpl.class);
	
//	private ReentrantLock lock = new ReentrantLock();
	@Autowired
	CertMapper cem;
	
	@Autowired
	BusiParamMapper bpm;
	
	@Autowired
	BusinessMapper bm;

	@Autowired
	BatchCollectionMapper bcm;

	@Autowired
	PersonalMapper pm;

	@Autowired
	CardBatchMapper cbm;

	@Autowired
	CardTaskMapper ctm;

	@Autowired
	CooperationCompanyMapper ccm;

	@Autowired
	CardProdunctDefinitionMapper cpdm;

	@Autowired
	CorporationMapper cm;

	@Autowired
	CardControlMapper cardm;

	@Autowired
	CardDataMapper cdm;
	
	@Autowired
	MainAccountPersonalMapper mapm;

	@Autowired
	ApplyCardService acs;

	@Autowired
	CooperationCompanyMapper cocm;
	
	@Autowired
	CertificateMapper cfm;
	
	@Autowired
	CardPhysicsTypeMapper cptm;
	
	@Autowired
	CardManageMapper cmm;
	
	@Autowired
	AppOpenRegMapper aorm;
	
	@Autowired
	SubaccountPersonalMapper spm;
	
	@Autowired
	BlackListGenMapper blgm;
	
	@Autowired
	BlackListRcMapper blrm;

	@Autowired
	FileStatusMapper fsm;

	@Autowired
	CardNoUseDetailMapper cndm;
	
	@Autowired
	CardNoGeneratedMapper cngm;
	
	@Autowired
	AppKindMapper akm;
//	@Autowired
//	SqlSessionTemplate sessionTemplate;
	
	
	public DwzPage<ImportBankFileVo> showBankFileList(ImportBankFileVo vo) throws ApplicationException{
//		String g=PathContants.HTTP_ROOT+PathContants.FTP_PATH_MAKECARDFILE+"/bank/"+vo.getBank()+"/"+vo.getFileType();
//		List<String> list = HtmlParseUtil.parseHtml(g);//目录下的文件列表
//		if(list.size()>0){
//			list.remove(0);
//		}
		String remotePath=PathContants.FTP_PATH_MAKECARDFILE+vo.getBank()+PathContants.separator+vo.getFileType();
		List<FTPFile> files = FtpUtil.getFileList(PathContants.FTP_URL, PathContants.FTP_PORT, PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, remotePath);//目录下的文件列表
		List<String>list=new ArrayList<>();
		for(FTPFile file:files){
			list.add(file.getName());
		}
		List<ImportBankFileVo> l1 =new ArrayList<>();//返回页面列表
		ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		List<FileStatus> fileStatus=fsm.queryAllByFileType(vo.getFileType());
		for(String fileName:list){
			boolean b=false;
			for(FileStatus fStatus:fileStatus){
				//文件在数据库中存在
				if(fileName.equals(fStatus.getFileName())){
					if(fStatus.getFileStatus().equals("0")){
						ImportBankFileVo v1 = new ImportBankFileVo();
						v1.setBank(vo.getBank());
						v1.setFileType(vo.getFileType());
						v1.setFileName(fStatus.getFileName());
						l1.add(v1);
					}
					b=true;
					break;
				}
			}
			//文件在数据库中不存在
			if(!b){
				FileStatus ff=new FileStatus();
				ff.setCrtDate(new Date());
				ff.setCrtOperator(activeUser.getUserNo().toString());
				ff.setFileName(fileName);
				ff.setFileType(vo.getFileType());
				ff.setFileStatus("0");
				fsm.insert(ff);
				
				ImportBankFileVo v1 = new ImportBankFileVo();
				v1.setBank(vo.getBank());
				v1.setFileType(vo.getFileType());
				v1.setFileName(fileName);
				l1.add(v1);
			}
		}
		
		ListPageUtil<ImportBankFileVo> lpu= new ListPageUtil<>(l1, vo.getCurrentPage(), vo.getNumPerPage());
		
		DwzPage<ImportBankFileVo> dp = new DwzPage<>(vo.getCurrentPage(), vo.getNumPerPage(),l1.size());
		dp.setList(lpu.getPagedList());	
		return dp;
	
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Boolean generatorCitizenCardNo(String cardpCode,String prefix, Integer num) throws Exception {
		List<String> list=new ArrayList<>();
		CardNoGenerated c=cngm.queryLastRecord(cardpCode);
		String fileSeq=null;//文件名序号
		String currentNo=null;
		int valid = 0;
		if (c == null) {
			currentNo="0000000";//市民卡号后7位
			fileSeq="0001";
		}else{
			currentNo=c.getEndSegmentNo();
			int a=c.getFileName().indexOf(".");
			fileSeq=CommonUtil.patchHexString(String.valueOf((Integer.valueOf(c.getFileName().substring(a-4, a))+1)), 4);
		}
		String dd=currentNo;//后7位
		for(int j=0;j<num;j++){
			String endNo = "";
			if (StringUtils.isNotEmpty(dd)) {
				endNo=dd;
			} else {
				throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "CitizenCardNo is null !!!");
			}
			logger.error("***************************上一条卡面号后7位*****：[{}]", dd);
			Integer newNo = Integer.parseInt(endNo) + 1;// 生成 后7位+1
			String gg = "";
			String s = "";
			int l = newNo.toString().length();
			if (endNo.indexOf("0") == 0 && l < 7) {
				int p = 7 - l;// 最后所需0的个数
				for (int i = 0; i < p; i++) {
					s += "0";
				}
				gg = s + newNo.toString();
			} else if (l == 7) {
				gg = newNo.toString();
			}

			valid = CardUtil.calcLuhn(prefix + gg);
			String newCardNo = prefix + valid + gg;// 组合卡面号
			if (CardUtil.verifyCardNo(newCardNo)) {
				list.add( newCardNo);
				dd=gg;
			}
			else {
				throw new ApplicationException(ErrorCode.DATA_ILLEGALITY, "卡面号不合法");
			}
		}
		String fileName=null;
		
//		String SrFileName=null;
		
		if(cardpCode.equals(CardContants.CARD_P_CODE_JS)){
			fileName="CN1200"+new SimpleDateFormat("yyMMdd").format(new Date())+fileSeq+".txt";
//			SrFileName="RJMK1200"+new SimpleDateFormat("yyMMdd").format(new Date())+fileSeq+".txt";
		}else if(cardpCode.equals(CardContants.CARD_P_CODE_WF)){
			fileName="CN1100"+new SimpleDateFormat("yyMMdd").format(new Date())+fileSeq+".txt";
		}	
		String path=null;
    	if(fileName.substring(2, 4).equals("11")){
    		path=PathContants.FTP_PATH_GENERATEDCARDNO+"WF_BANK"+PathContants.separator+"CN";
    	}if(fileName.substring(2, 4).equals("12")){
    		path=PathContants.FTP_PATH_GENERATEDCARDNO+"JS_BANK"+PathContants.separator+"CN";
    	}
		boolean b=false;
		logger.debug("卡号生成数量=="+list.size());
		if(cardpCode.equals(CardContants.CARD_P_CODE_JS)){
			//上传卡号库文件
//			boolean bb=FileUtil.generatedCardNoText(list, fileName);
			b=FileUtil.generatedCardNoText(list, fileName,path);
//			if(bb){
//				//上传制卡文件FTP
//				int port=PathContants.FTP_PORT;
//		    	String username=PathContants.FTP_USERNAME;
//		    	String password=PathContants.FTP_PASSWORD;
//		    	StringBuffer sBuffer=generatorMakeCardData(list,CardContants.CARD_P_CODE_JS);
//		    	ByteArrayInputStream input=new ByteArrayInputStream(sBuffer.toString().getBytes());
//		    	String path=PathContants.FTP_PATH_GENERATEDCARDNO+PathContants.separator+"JS_BANK"+File.separator+"SR";
//				b=FtpUtil.uploadFile(PathContants.FTP_URL, port, username, password, path, SrFileName, input);
//			}
		}else if(cardpCode.equals(CardContants.CARD_P_CODE_WF)){
			b=FileUtil.generatedCardNoText(list, fileName,path);
		}
		if(b){
			if(list.size()==num){
				CardNoGenerated cardNoGenerated=new CardNoGenerated();
				cardNoGenerated.setCardpCode(cardpCode);
				cardNoGenerated.setCrtDate(new Date());
				cardNoGenerated.setEndSegmentNo(list.get(list.size()-1).substring(5));
				cardNoGenerated.setStartSegmentNo(list.get(0).substring(5));
				cardNoGenerated.setNum(num);
				cardNoGenerated.setFileName(fileName);
				cardNoGenerated.setUsedSegmentNo(0);
				cardNoGenerated.setIsUseUp("0");
				cardNoGenerated.setCardPhysicalType(prefix.substring(2,3));
				cngm.insert(cardNoGenerated);
			}
		}
		return b;
		
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void readFileInfoByBank(ImportBankFileVo vo) throws Exception {
		if(vo.getFileName().isEmpty()){
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL,"fileName is null" );
		}
		String remotePath=PathContants.FTP_PATH_MAKECARDFILE+PathContants.separator+vo.getBank()+PathContants.separator+vo.getFileType();
		//InputStream in =HttpUtil.getInputStream(g);
		InputStream in=FtpUtil.getInputStream(PathContants.FTP_URL, PathContants.FTP_PORT, PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, remotePath, vo.getFileName()+".txt");
		List<String>list = HttpUtil.getStreamString(in);//文件内容
		list.remove(0);//去掉标题
		if(BankFileContants.CARDNO_FILE.equalsIgnoreCase(vo.getFileType())){//银行提供的申请信息
			//任务生成
			applyAndGeneratCardMakeTaskNew(list, vo);
			
			FileStatus fileStatus=new FileStatus();
			fileStatus.setFileStatus("1");
			fileStatus.setFileName(vo.getFileName()+".txt");
			fsm.updateByFileName(fileStatus);
			
		}else if(BankFileContants.MAKECARD_REFILE.equalsIgnoreCase(vo.getFileType())){//返回的制卡文件
			//完成制卡任务
			if(vo.getBank().equals("WF_BANK")){
				returnMakeCardTaskByWF(list, vo);
			}else if(vo.getBank().equals("JS_BANK")){
				//现在业务和潍坊银行一致
				returnMakeCardTaskByWF(list, vo);
			}
//			以前使用
//			else if(vo.getBank().equals("JS_BANK")){
//				String fileName="BTC-JS"+vo.getFileName().substring(8);
//				String path=PathContants.HTTP_ROOT+PathContants.FTP_PATH_MAKECARDFILE+File.separator+vo.getBank()+File.separator+"BTC"+File.separator+fileName+".txt";
//				InputStream inputStream =HttpUtil.getInputStream(path);
//				String path=PathContants.FTP_PATH_MAKECARDFILE+File.separator+vo.getBank()+File.separator+"BTC";
//				InputStream inputStream=FtpUtil.getInputStream(PathContants.FTP_URL, PathContants.FTP_PORT, PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, path, fileName+".txt");
//				List<String>cardInfos = HttpUtil.getStreamString(inputStream);//文件内容
//				cardInfos.remove(0);//去掉标题
//				returnMakeCardTaskByJS(list, cardInfos, vo);
//			}
			
			//更新文件状态
			FileStatus fileStatus=new FileStatus();
			fileStatus.setFileStatus("1");
			fileStatus.setFileName(vo.getFileName()+".txt");
			fsm.updateByFileName(fileStatus);
		}else if(BankFileContants.CARD_USE_FILE.equalsIgnoreCase(vo.getFileType())){//银行卡开卡数据文件
			//发卡信息
			returnActivateCardInfo(list,vo);
			//更新文件状态
			FileStatus fileStatus=new FileStatus();
			fileStatus.setFileStatus("1");
			fileStatus.setFileName(vo.getFileName()+".txt");
			fsm.updateByFileName(fileStatus);
		}
		else if(BankFileContants.CARD_BUS_FILE_GHX.equalsIgnoreCase(vo.getFileType())){//挂失注销市民卡信息文件
			//更挂失注销信息
			updateLossCancleStatus(list,vo);	
			//更新文件状态
			FileStatus fileStatus=new FileStatus();
			fileStatus.setFileStatus("1");
			fileStatus.setFileName(vo.getFileName()+".txt");
			fsm.updateByFileName(fileStatus);
		}else if(BankFileContants.CARD_BUS_FILE_SCX.equalsIgnoreCase(vo.getFileType())){//挂失注销市民卡信息文件
			//补换卡失信息
			updateChangeSupplemrntStatus(list, vo);	
			//更新文件状态
			FileStatus fileStatus=new FileStatus();
			fileStatus.setFileStatus("1");
			fileStatus.setFileName(vo.getFileName()+".txt");
			fsm.updateByFileName(fileStatus);
		}

	}
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void applyAndGeneratCardMakeTaskNew(List<String>list,ImportBankFileVo vv) throws Exception{
		
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		
		Date now =new Date();
		String cardpCode=null;
		CardProdunctDefinition cpd=null;
		String copBankNo="";//合作银行（卡发行商代码）
		String companyNo="";//制卡商编号
		if("JS_BANK".equalsIgnoreCase(vv.getBank())){
			 copBankNo = CardContants.CARD_PUBLISHER_CODE_JS;
			 companyNo=CardContants.MAKECARD_COMPANY_NO_JS;
//			 cpd= cpdm.queryCardProdunctDefinitionByCardPublisherCode(copBankNo).get(0);
			 cardpCode=CardContants.CARD_P_CODE_JS;
			 
		}else if("WF_BANK".equalsIgnoreCase(vv.getBank())){
			 copBankNo = CardContants.CARD_PUBLISHER_CODE_WF;
			 companyNo=CardContants.MAKECARD_COMPANY_NO_WF;
//			 cpd=cpdm.queryCardProdunctDefinitionByCardPublisherCode(copBankNo).get(0);
			 cardpCode=CardContants.CARD_P_CODE_WF;
		}
		
		cpd=cpdm.queryCardPCode(cardpCode);
		//未使用完的卡号段
		List<CardNoGenerated> cardNoGenerateds= cngm.queryAllRecordByCardpCode(cardpCode);
		
	//验证银行的卡号段是否已经使用
		//所有卡号段使用明细
		List<CardNoUseDetail> details=cndm.queryAllByCardpCode(cardpCode);
		int num=Integer.valueOf(list.get(0).split("\\|")[0]);
		//制卡卡号段（后面需要subString()）
		int startSegmentNo=Integer.valueOf(list.get(0).split("\\|")[1].substring(5));
		int endSegmentNo=Integer.valueOf(list.get(0).split("\\|")[2].substring(5));
		
		if(num!=(endSegmentNo-startSegmentNo+1)){
			throw new ApplicationException(ErrorCode.DATA_ILLEGALITY, "数据不合法");
		}
		if(details!=null){
			for(CardNoUseDetail detail :details){
				int currEndSegmentNo=Integer.valueOf(detail.getEndSegmentNo());
	    		int currStartSegmentNo=Integer.valueOf(detail.getStartSegmentNo());
				if(startSegmentNo>=currStartSegmentNo&&startSegmentNo<=currEndSegmentNo){
					throw new ApplicationException(ErrorCode.CAERD_SEGMENT_USEING,"card_segment_useing");
				}
				if(endSegmentNo>=currStartSegmentNo&&endSegmentNo<=currEndSegmentNo){
					throw new ApplicationException(ErrorCode.CAERD_SEGMENT_USEING,"card_segment_useing");
				}
			}
		}
		
		//获取卡号段对应的文件名
		List<String> fileNames=FileUtil.getFileByCardNoSegment(startSegmentNo, endSegmentNo, cardNoGenerateds);
		//拿到的卡号
		List<String> cardNos = FileUtil.getCardNoByFileName(startSegmentNo,endSegmentNo, fileNames);
		
	//更新卡号段使用情况,在方法最后执行
    	//将没有用到的记录去掉
		List<CardNoGenerated> newcardNoGenerateds=new ArrayList<>();
		for(int i=0;i<cardNoGenerateds.size();i++){			
			if(fileNames.contains(cardNoGenerateds.get(i).getFileName())){
				newcardNoGenerateds.add(cardNoGenerateds.get(i));
			}
		}
//		for(CardNoGenerated c:cardNoGenerateds){
//			if(!fileNames.contains(c.getFileName())){
//				cardNoGenerateds.remove(this);
//			}
//		}
							
//		批量采集表
//		BatchCollection bc = new BatchCollection();
//		bc.setApplyBatchNo(vv.getFileName());
//		bc.setCardPCode(cardpCode);
//		bc.setCollBranchName(activeUser.getBranchName());// 采集网店名称
//		bc.setCollBranchNo(activeUser.getBranchNo());// 采集网点编号
//		bc.setCrtDate(now);
//		bc.setCrtOperator(activeUser.getUserNo().toString());
//		bc.setLastDate(now);
//		bc.setLastOperator(activeUser.getUserNo().toString());
//		bc.setOriginType(CardContants.DATA_ORIGIN_INPUT_BY_BANK);// 来源，后面可能要改成code1,code2...
//		bc.setRecordNum(cardNos.size());// 记录申请数量
//		Calendar ccc = Calendar.getInstance();
//		ccc.setTime(now);
//		ccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());// 今天+n天===预计领卡日期
//		bc.setApplyDate(now);
//		bcm.saveBCollection(bc);
		
		String prevTaskNO=ctm.queryPreviousTaskNo();//上一个任务编号
		CardTask ct = new CardTask();
		ct.setCardTaskNo(SequenceNumberUtil.getSequenceNumber(cpd.getCardpCode(),prevTaskNO));//制卡任务编号
		ct.setApplyBranchNo(activeUser.getBranchNo());// 申领网点编号
		ct.setApplyBranch(activeUser.getBranchName());// 申领网点名称
//		ct.setBatchMarkerNo(cb.getBatchMarkerNo());//制作批次号
		ct.setCardpCode(cpd.getCardpCode());
		ct.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码
		ct.setCompanyNo(companyNo);// 制卡厂商编号

		ct.setCorpCode(copBankNo);//单位代码
		ct.setCorpName(copBankNo.equals(CardContants.CARD_PUBLISHER_CODE_JS)==true?"建设银行":"潍坊银行");//单位名称
		ct.setIsUrgent("N");// 默认不加急  是否加急
		ct.setRecordNum(cardNos.size());// 记录数量
		ct.setRemark("银行预制卡任务");// 备注
//		ct.setRollbackDate(rollbackDate);//回退日期
//		ct.setRollbackSn(rollbackSn);//回退日志流水号
//		ct.setRollbackStatus(rollbackStatus);//回退标志
		ct.setTaskName(vv.getFileName());// 任务名称
		ct.setTaskPerType(CardContants.EXECUTION_MODE_OUTSOURCE);// 任务执行方式 外包 本地
		ct.setTasksGeneTime(now);// 任务产生时间
		ct.setTasksOperator(activeUser.getUserNo().toString());//
		ct.setTaskStatus(CardContants.TASK_GENERATION);// 任务状态
		ct.setTaskType(CardContants.TASK_TYPE_NO_NAME_CARD);// 任务类型 1-记名卡任务  2-不记名任务
		ctm.insert(ct);	

		Calendar cccc = Calendar.getInstance();
		cccc.setTime(now);
		cccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());// 今天+n天===预计领卡日期
		long start = System.currentTimeMillis();
		
		List<CardData> cardDatas=new ArrayList<>();
		List<CardControl> cardControls=new ArrayList<>();
		List<CardManage> cardManages=new ArrayList<>();
		List<Business> businesses=new ArrayList<>();
		List<Cert>certs=new ArrayList<>();
		int flag=1;
		//处理卡相关业务
		for(String str:cardNos){
			CardData cd = new CardData();
			cd.setCardpCode(cardpCode);
			cd.setCitizenCardNo(str);
			cd.setCardTypecode(cpd.getCardTypeCode());
			cd.setCardValidTime(CommonUtil.willDate(now, cpd.getCardValidTime()));
			cd.setCopBankNo(copBankNo);
			cd.setCardPhysicalType("0");//标准IC卡
			cd.setFlag(flag);
			cardDatas.add(cd);
			
			// 业务流水表
			Business b = new Business();
			b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
//			b.setAgentName(agentName);//代理人姓名
//			b.setAgentPaperNo(agentPaperNo);//代理人证件号码
//			b.setAgentPapertype(agentPapertype);//代理人证件类型
//			b.setAgentPhone(agentPhone);// 代理人联系电话
//			b.setBatchNo(batchNo);//批次号
//			b.setBusiNum(1);// 业务数量
//			b.setCardControlId(cc.getCardControlId());// 卡控制号
			b.setCardpCode(cd.getCardpCode());// 卡产品
//			b.setCertNo(ce.getCertNo());// 凭证编号
//			b.setCorpNo(corpNo);//单位编号 批量办理时使用
//			b.setCustomerNo(p.getCustomerNo());// 客户编号
			b.setRemark("银行卡制卡任务生成");// 备注
//			b.setRptDate(rptDate);//轧帐日期
//			b.setRptFlag(rptFlag);//轧帐标识
			b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
			b.setTransAuthId("业务授权人编号001");// 业务授权人编号
			b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
			b.setTransCode("交易代码");//
			b.setTransDate(new Date());//交易日期
			b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况	
			b.setFlag(flag);
			
			
			//卡过程
			CardManage cme = new CardManage();
			String uuid=(UUID.randomUUID().toString()).replace("-", "");
			cme.setProcessId(uuid);
			cme.setCardpCode(cardpCode);
			cme.setBusinessNo(b.getBusinessNo());
			cme.setApplyBranch(activeUser.getBranchName());
			cme.setApplyBranchNo(activeUser.getBranchNo());
			cme.setApplyDate(now);
			cme.setApplyTellerNo(activeUser.getUserNo().toString());
			cme.setCardPosition(CardContants.CARD_MAKE_ROOM);
			cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
			cme.setCardTaskNo(ct.getCardTaskNo());
//			cme.setProcessCode(CardContants.CARD_PROC_MAKING);
//			cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_CARD_PEND));
			cme.setCitizenCardNo(str);
			cme.setRemark("银行卡制卡任务生成");
			cme.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cme.setFlag(flag);
			cardManages.add(cme);
			
			CardControl cc = new  CardControl();
			cc.setClaimStatus(CardContants.CLAIM_STATUS_MAKING);
			cc.setCardStatus(CardContants.CARD_STATE_DISABLED);
			cc.setCurrProcId(cme.getProcessId());// 申领状态：制卡
			cc.setCardPosition(CardContants.CARD_MAKE_ROOM);// 卡位置：制卡间
			cc.setCardTaskNo(ct.getCardTaskNo());
			cc.setApplyDate(cccc.getTime());// 预计林卡日期
			// cc.setCardDate(cardDate);//制卡日期
			cc.setCrtDate(now);
			cc.setCrtOperator(activeUser.getUserNo().toString());
			cc.setLastDate(now);
			cc.setLastOperator(activeUser.getUserNo().toString());
			cc.setDmgFlag(CardContants.CARD_UNDAMAGED);	// 卡损坏状况
														// 0-未损坏，1-非人为损坏，2-人为损坏
			// cc.setLogoutDate(logoutDate);//注销日期
			// cc.setLogoutReason(logoutReason);//注销原因
			// cc.setReleaseDate(ccc.getTime());//发卡日期
			cc.setRemark("银行联名卡卡控制表");
			cc.setApplyType(CardContants.APPLY_TYPE_FIRST);
			cc.setFlag(flag);
			cardControls.add(cc);
			
//			 凭证表
			Cert ce = new Cert();
			ce.setCertNo(SequenceNumberUtil.generatorCertNo());
			ce.setBranch(activeUser.getBranchName());// 网点名称
			ce.setBranchNo(activeUser.getBranchNo());// 网点编号
			ce.setBusinessNo(b.getBusinessNo());//业务流水号
//			ce.setCardControlId(cc.getCardControlId());
			ce.setCertType(CardContants.SINGLE_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请
															// 3 出库配送 4 单笔发卡 5
															// 批量发卡
			ce.setCardpCode(cardpCode);// 卡产品代码
			ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
														// 3.非记名衍生卡
			ce.setCorpCode(copBankNo);// 单位编号id
			ce.setCorpName(copBankNo.equals(CardContants.CARD_PUBLISHER_CODE_JS)==true?"建设银行":"潍坊银行");// 单位名称
			ce.setCrtDate(now);
			ce.setCrtOperator(activeUser.getUserNo().toString());
			ce.setData("银行联名卡申请凭证 ");// 打印凭证数据
			ce.setLastDate(now);
			ce.setLastOperator(activeUser.getUserNo().toString());
//			ce.setName(p.getCustomerName());// 持卡人姓名
//			ce.setPaperNo(p.getPaperNo());
//			ce.setPaperType(p.getPaperType());
			ce.setPrintCount(0);// 打印次数
//			ce.setTransCode(transCode);//交易代码
			ce.setFlag(flag);	
			certs.add(ce);
			
			b.setCertNo(ce.getCertNo());
			cme.setCertNo(ce.getCertNo());
			businesses.add(b);
			flag++;	
		}
		cdm.batchInsert(cardDatas);		
		cmm.batchInsert(cardManages);
		for(CardControl c:cardControls){
			for(CardData data:cardDatas){
				if(c.getFlag()==data.getFlag()){
					c.setCardDataId(data.getCardDataId());
					break;
				}
			}
		}		
		cardm.batchInsert(cardControls);
		for(Business b:businesses){
			for(CardControl c:cardControls){
				if(c.getFlag()==b.getFlag()){
					b.setCardControlId(c.getCardControlId());
				}
			}
		}
		for(Cert cert:certs){
			for(CardControl c:cardControls){
				if(c.getFlag()==cert.getFlag()){
					cert.setCardControlId(c.getCardControlId());
				}
			}
		}
		bm.batchInsert(businesses);
		cem.batchInsert(certs);
		
		long end = System.currentTimeMillis();
		logger.debug("----all-----------" + (start - end) + "---------------");
		updateCardNoUse(startSegmentNo, endSegmentNo, newcardNoGenerateds, cardpCode);

	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public List<String> exportBankMakeCardFile(String root,List<MakeCardQueryResultVo> list) throws ApplicationException {
		//root存放了2条路径，使用时要当心（项目绝对根路径和相对路径）
		Date now = new Date();
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
			
		
		//验证信息
		Set<String> set1 = exceptions(list); 
		//上一条制卡批次
		CardBatch cardBatch = cbm.queryFirstCardBatch();
	
		long start = System.currentTimeMillis();
		List<String> ls=new ArrayList<>();
		for(MakeCardQueryResultVo mcv:list){
			StringBuffer sb = new  StringBuffer();
			String  cardTaskNo = mcv.getCardTaskNo();
			List<CardData> cDatas=cdm.queryCardDataByCardTaskNo_list(cardTaskNo);
			String citizenCardNo =cDatas.get(0).getCitizenCardNo();
			String prefix = citizenCardNo.substring(0, 4);
			
			//制卡批次号
			String batchMarkerNo = SequenceNumberUtil.generatorCardBatchKey(cardBatch);
			
			//文件名
			String name_1="RJMK"+prefix+batchMarkerNo;
			String fileName = "RJMK"+prefix+batchMarkerNo+".txt";
			
			//保存制卡批次表
			CardBatch cb = new CardBatch();
			 cb.setBatchMarkerNo(batchMarkerNo);//制作批次号  yyMMdd+4位序号
			// cb.setBackRecDate(backRecDate);//返回接收日期
			// cb.setBackReceiver(backReceiver);//返回接收人
			 String companyName="";//制卡商
			 Iterator<String> it = set1.iterator();
			 while(it.hasNext()){
				 companyName = it.next();
			 }
			CooperationCompany ccom = cocm.queryCooperationCompanyByCompanyName(companyName);
			cb.setDataReceiver(ccom.getCompanyType());// 数据接收方 就是 银行、制卡商
			cb.setDataSendDate(new Date());// 数据发送日期
			cb.setDataSender(activeUser.getUserNo().toString());// 数据发送人
			cb.setExportNum(1);// 导出次数
			cb.setFileName(fileName);//文件名
			cb.setPerformType(CardContants.EXECUTION_MODE_OUTSOURCE);// 执行方式
			cb.setSupplierCode(ccom.getCompanyNo());//制卡厂商编号
			cbm.insert(cb);
			//更新任务
			CardTask ct = ctm.queryCardTaskByCardTaskNo(cardTaskNo);
			ct.setTaskStatus(CardContants.EXPORTED_CARD_FILE);
			ct.setBatchMarkerNo(cb.getBatchMarkerNo());
			ctm.updateCardTask(ct);
			
			cardBatch=cb;
			
			//卡相关
			int flag=1;
			List<CardControl> ll = cardm.queryCardControlByCardTaskNo(cardTaskNo);
			//批量插入集合
//			List<CardControl> cardControls=new ArrayList<>();
			List<CardManage> cardManages=new ArrayList<>();
			List<Business> businesses=new ArrayList<>();
			for(CardControl cc :ll){
				CardData c=null;				
				for(CardData cardData:cDatas){
					if(cc.getCardDataId().intValue()==cardData.getCardDataId().intValue()){
						c=cardData;
						break;
					}
				}
				Business b = new Business();
				b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
//				b.setAgentName(agentName);//代理人姓名
//				b.setAgentPaperNo(agentPaperNo);//代理人证件号码
//				b.setAgentPapertype(agentPapertype);//代理人证件类型
//				b.setAgentPhone(agentPhone);// 代理人联系电话
//				b.setBatchNo(batchNo);//批次号
//				b.setBusiNum(1);// 业务数量
				b.setCardControlId(cc.getCardControlId());// 卡控制号
				b.setCardpCode(c.getCardpCode());// 卡产品
//				b.setCertNo(ce.getCertNo());// 凭证编号
//				b.setCorpNo(corpNo);//单位编号 批量办理时使用
//				b.setCustomerNo(p.getCustomerNo());// 客户编号
				b.setRemark("银卡制卡任务导出");// 备注
//				b.setRptDate(rptDate);//轧帐日期
//				b.setRptFlag(rptFlag);//轧帐标识
				b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
				b.setTransAuthId("业务授权人编号001");// 业务授权人编号
				b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
				b.setTransCode("交易代码");//
				b.setTransDate(new Date());//交易日期
				b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况	
				businesses.add(b);
				CardManage cme = new CardManage();
				String uuid=(UUID.randomUUID().toString()).replace("-", "");
				cme.setProcessId(uuid);
				cme.setApplyBranch(activeUser.getBranchName());
				cme.setApplyBranchNo(activeUser.getBranchNo());
				cme.setApplyDate(now);
				cme.setApplyTellerNo(activeUser.getUserNo().toString());
				cme.setCardpCode(c.getCardpCode());
				cme.setCardPosition(CardContants.CARD_MAKE_ROOM);
				cme.setCardStatus(cc.getCardStatus());
				cme.setCardTaskNo(cardTaskNo);
				cme.setBusinessNo(b.getBusinessNo());
//				cme.setCustomerNo(customerNo);
				cme.setRemark("银行卡制卡任务导出");
//				cme.setProcessCode(CardContants.CARD_PROC_MAKING);
//				cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_MAKING));				
				cme.setCitizenCardNo(c.getCitizenCardNo());
				cme.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
				cardManages.add(cme);
				
				
				cc.setClaimStatus(CardContants.CLAIM_STATUS_MAKING);				
				cc.setCurrProcId(cme.getProcessId());// 申领状态：制卡
				cc.setCardPosition(CardContants.CARD_MAKE_ROOM);// 卡位置：制卡间
				cc.setFlag(flag);
//				cardControls.add(cc);
								
				// 业务流水表
				
			}
			cmm.batchInsert(cardManages);
			bm.batchInsert(businesses);
			cardm.batchUpdate(ll);
			
			long end = System.currentTimeMillis();
			logger.debug("----all-----------" + (start - end) + "---------------");
			
			String bankType="";
			if(ct.getCorpCode().equals(CardContants.CARD_PUBLISHER_CODE_JS)){
				bankType="JS_BANK";
			}else if(ct.getCorpCode().equals(CardContants.CARD_PUBLISHER_CODE_WF)){
				bankType="WF_BANK";
			}
			//不记名任务
//			MakeCardInfo2  m = new MakeCardInfo2();
//			m.setCardTaskNo(cardTaskNo);
//			m.setCityCode("2625");
//			Integer count  = ct.getRecordNum();
//			m.setRecordAmount(count.toString());
//			String startNumber =citizenCardNo;
//			m.setStartNumber(startNumber);
//			Integer lastId = cd.getCardDataId()+count-1;
//			m.setStopNumber(cDatas.get(cDatas.size()-1).getCitizenCardNo());
//			m.setCardType(startNumber.substring(0, 4));
//			sb.append(m.toString());
			//记名任务
			List<String> cardNos=new ArrayList<>();//卡号集合
			for(CardData c:cDatas){
				cardNos.add(c.getCitizenCardNo());			
			}
			sb=generatorMakeCardData(cardNos, CardContants.CARD_P_CODE_WF);
			String fileProjectpath =PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+bankType+File.separator+name_1+File.separator+fileName;
			FileUtil.contentToTxt(root.split("\\|")[0] + fileProjectpath, sb.toString(), FileUtil.str);
			String zipName= name_1+".zip";
			String zipPath = root.split("\\|")[0] + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+bankType+File.separator+name_1+File.separator+zipName;
			ZipUtil.createZip(root.split("\\|")[0] + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+bankType+File.separator+name_1+File.separator+fileName, zipPath);

			ls.add(root.split("\\|")[1]+PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+bankType+File.separator+name_1+File.separator+zipName);
		}
		return ls;
	}

	/**验证信息**/
	private Set<String> exceptions(List<MakeCardQueryResultVo> list) throws ApplicationException{
		if(list.size()<0){
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "data  is  null!!!");
		}
		Set<String> set = new HashSet<>();//卡产品
		Set<String> set1 = new HashSet<>(); //制卡单位
		Set<String> set2 = new HashSet<>(); // 卡物理类型
		for (MakeCardQueryResultVo mqv : list) {
			set.add(mqv.getCardPName());
			set1.add(mqv.getCorp());
			set2.add(mqv.getCardPhysicsTypeCode());
		}
		
		if(set.size()>1){
			throw new ApplicationException(ErrorCode.DATA_NOT_MATCH, "data more than 1,cardP   do not match!!!");
		}
		
		if(set1.size()>1){
			throw new ApplicationException(ErrorCode.DATA_NOT_MATCH, "data more than 1,make card unit or bank  do not match!!!");
		}
		
		if(set2.size()>1){
			throw new ApplicationException(ErrorCode.DATA_NOT_MATCH, "data more than 1,cardPhysicalType  do not match!!!");
		}
		return set1;
	}
	
	/**
	 * 生成银行制卡数据
	 * @param list 卡号集合
	 * @param cardpCode
	 * @return
	 */
	private StringBuffer generatorMakeCardData(List<String> list,String cardpCode){
		StringBuffer sb=new StringBuffer();
		if(cardpCode.equals(CardContants.CARD_P_CODE_JS)){
			sb.append(FileUtil.cardTitle(FileUtil.str));
		}
		int i=1;
		for(String citizenCardNo:list){
			MakeCardInfo mci = new MakeCardInfo();			
			//卡片信息
			String acsCitizenCardNo = CommonUtil.stringToAscii(citizenCardNo); //长度24
			
			String end8 = citizenCardNo.substring(4);
			
			String appSeqNo = CardContants.CITY_CODE+ CommonUtil.stringToAscii(end8) ;//以下的所有应用序列号  2625+卡面号后8字节ascii
			
			String cardType=Integer.toHexString(Integer.valueOf(cardpCode)).toUpperCase();//卡类型  就是卡产品代码转16进制 
			if(cardType.length() == 1 ){
				cardType = "0"+cardType;
			}
//			mci.setCardholderType_3F000005(cardType);//3F00.0005.卡主类型
			mci.setCitizenCardNo_3F000005(acsCitizenCardNo);//3F00.0005.市民卡卡号   长度24
			mci.setApplicationSequenceNumber_3F010015(appSeqNo);//3F01.0015.应用序列号     2625+卡面号后8字节ascii
//			mci.setCardType_3F010015(cardType);// 3F01.0015.卡类型
			mci.setApplicationSequenceNumber_3F020015(appSeqNo);//3F02.0015.应用序列号
			mci.setCardType_3F020015(cardType);//3F02.0015.卡类型
			mci.setApplicationSequenceNo_3F100015(appSeqNo);//3F10.0015.应用序列号
			mci.setApplicationSequenceNumber_9A000015(appSeqNo);// 9A00.0015.应用序列号
			mci.setCardType_9A000015(cardType);//9A00.0015.卡类型
			if(i<list.size()){
				sb.append(mci.toString());
			}
			else if(i==list.size()){
				Pattern p = Pattern.compile("\r\n");
		        Matcher m = p.matcher(mci.toString());
		        sb.append(m.replaceAll(""));
			
			}
			i++;
		}
		logger.debug("制卡数据生成stringbuffer"+list.size());
		return sb;
	}
	
	/**
	 * 更新卡号使用情况
	 * @param startSegmentNo
	 * @param endSegmentNo
	 * @param cardNoGenerateds
	 */
	private void updateCardNoUse(int startSegmentNo ,int endSegmentNo,List<CardNoGenerated> cardNoGenerateds,String cardpCode){
		Date now =new Date();
		for(CardNoGenerated c:cardNoGenerateds){
			int currEndSegmentNo=Integer.valueOf(c.getEndSegmentNo());
    		int currStartSegmentNo=Integer.valueOf(c.getStartSegmentNo());
    		//制卡卡号段包含制卡文件卡号段
			if(startSegmentNo<currStartSegmentNo&&endSegmentNo>currEndSegmentNo){
				CardNoGenerated cardNoGenerated=new CardNoGenerated();
	    		cardNoGenerated.setId(c.getId());
				cardNoGenerated.setUsedSegmentNo(c.getNum());
				cardNoGenerated.setIsUseUp("1");				
				cngm.updateByPrimaryKey(cardNoGenerated);
				
				CardNoUseDetail detail=new CardNoUseDetail();
				detail.setStartSegmentNo(c.getStartSegmentNo());
				detail.setEndSegmentNo(c.getEndSegmentNo());
				detail.setCardnoGeneratId(c.getId());
				detail.setCardpCode(cardpCode);
				detail.setNum(c.getNum());
				detail.setCrtDate(now);
				cndm.insert(detail);
			}
			//制卡卡号段在制卡文件卡号段内
			if(startSegmentNo>=currStartSegmentNo&&endSegmentNo<=currEndSegmentNo){
				Integer cc=cndm.queryCountUsedByCardnoGeneratId(c.getId());
				int count=(cc==null?0:cc.intValue());
				int sum=count+(endSegmentNo-startSegmentNo+1);
				
				CardNoGenerated cardNoGenerated=new CardNoGenerated();
	    		cardNoGenerated.setId(c.getId());
    			cardNoGenerated.setUsedSegmentNo(sum);
				cardNoGenerated.setIsUseUp(sum==c.getNum()?"1":"0");					
				cngm.updateByPrimaryKey(cardNoGenerated);
				
				CardNoUseDetail detail=new CardNoUseDetail();
				detail.setStartSegmentNo(CommonUtil.patchHexString(String.valueOf(startSegmentNo), 7));
				detail.setEndSegmentNo(CommonUtil.patchHexString(String.valueOf(endSegmentNo), 7));
				detail.setCardnoGeneratId(c.getId());
				detail.setCardpCode(cardpCode);
				detail.setNum(endSegmentNo-startSegmentNo+1);
				detail.setCrtDate(now);
				cndm.insert(detail);
			}
			
			//制卡卡号开始段在文件中(仅仅开始段)
			if(startSegmentNo>=currStartSegmentNo&&startSegmentNo<=currEndSegmentNo
					&&endSegmentNo>currEndSegmentNo){
				Integer cc=cndm.queryCountUsedByCardnoGeneratId(c.getId());
				int count=(cc==null?0:cc.intValue());
				int sum=count+(currEndSegmentNo-startSegmentNo+1);
				CardNoGenerated cardNoGenerated=new CardNoGenerated();
	    		cardNoGenerated.setId(c.getId());
    			cardNoGenerated.setUsedSegmentNo(sum);
				cardNoGenerated.setIsUseUp(sum==c.getNum()?"1":"0");					
				cngm.updateByPrimaryKey(cardNoGenerated);
				
				CardNoUseDetail detail=new CardNoUseDetail();
				detail.setStartSegmentNo(CommonUtil.patchHexString(String.valueOf(startSegmentNo), 7));
				detail.setEndSegmentNo(c.getEndSegmentNo());
				detail.setCardnoGeneratId(c.getId());
				detail.setCardpCode(cardpCode);
				detail.setNum(currEndSegmentNo-startSegmentNo+1);
				detail.setCrtDate(now);
				cndm.insert(detail);	
			}
			
			//制卡卡号结束段在文件中(仅仅结束段)
			if(startSegmentNo<currStartSegmentNo&&endSegmentNo>=currStartSegmentNo
					&&endSegmentNo<=currEndSegmentNo){
				Integer cc=cndm.queryCountUsedByCardnoGeneratId(c.getId());
				int count=(cc==null?0:cc.intValue());
				int sum=count+(endSegmentNo-currStartSegmentNo+1);
				CardNoGenerated cardNoGenerated=new CardNoGenerated();
	    		cardNoGenerated.setId(c.getId());
    			cardNoGenerated.setUsedSegmentNo(sum);
				cardNoGenerated.setIsUseUp(sum==c.getNum()?"1":"0");					
				cngm.updateByPrimaryKey(cardNoGenerated);
				
				CardNoUseDetail detail=new CardNoUseDetail();
				detail.setStartSegmentNo(c.getStartSegmentNo());
				detail.setEndSegmentNo(CommonUtil.patchHexString(String.valueOf(endSegmentNo), 7));
				detail.setCardnoGeneratId(c.getId());
				detail.setCardpCode(cardpCode);
				detail.setNum(endSegmentNo-currStartSegmentNo+1);
				detail.setCrtDate(now);
				cndm.insert(detail);	
			}
		}
	}
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void returnMakeCardTaskByWF(List<String> list, ImportBankFileVo vv) throws ParseException {
		ActiveUser activeUser = null;
		Date now = new Date();
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
//		Date now = new Date();
		List<CardControl> cardControls=null;//卡控制表
		List<CardData> cardDatas=null;//卡数据表
		List<CardManage> cardManages=new ArrayList<>();//卡过程表
		List<Business> businesses=new ArrayList<>();//卡业务流水表
		CardTask ct=null;
		CardBatch cb=null;
		boolean f=true;
		for(String str:list){
			String [] info = StringUtils.splitPreserveAllTokens(str, "|");
			MakeCardFileReturnFileVo vo= new MakeCardFileReturnFileVo();
			vo.setFileName(info[0]);//制卡文件名--无后缀
			vo.setChipsLessNo(info[1]);//非接触芯片号
			vo.setChipsLessPin(info[2]);//非接片PIN
			vo.setCitizenCardNo(CommonUtil.AsciiStringToString(info[3]));//市民卡卡面号
			vo.setReturnDate(info[4]);//返回日期
			vo.setCardSeqNo(info[5]);//卡片序列号
			vo.setBcNo(info[6]);//银行卡号
			vo.setBcValidTime(info[7]);//银行卡有效期
			vo.setMakeCardResult(info[8]);//制卡结果
			vo.setMakeCardFailReason(info[9]);//制卡失败原因
//			vo.setOriMakeCardData(info[10]);//原卡数据暂时不用
			if(f){
				//任务
				ct = ctm.queryCardTaskByFileName(vv.getFileName().replace("Q", "R")+".txt");
				ct.setTaskStatus(CardContants.BANK_RETURN);
				ctm.updateCardTask(ct);
				cb = cbm.queryCardBatchByBatchMarkerNo(ct.getBatchMarkerNo());
				cb.setBackReceiver(activeUser.getUserNo().toString());
				cb.setBackRecDate(formatDate(vo.getReturnDate()));
				//cb.setFileName(vv.getFileName());
				cbm.update(cb);
				cardControls=cardm.queryCardControlByCardTaskNo(ct.getCardTaskNo());
				cardDatas=cdm.queryCardDataByCardTaskNo_list(ct.getCardTaskNo());
				f=false;
			}
			//卡制卡成功
			if(CardContants.MAKE_CARD_RESULT_SUCCESS.equals(vo.getMakeCardResult())){
				for(CardData cardData:cardDatas){
					if(cardData.getCitizenCardNo().equals(vo.getCitizenCardNo())){
						cardData.setCardSeqNo(vo.getCardSeqNo());
						cardData.setBcValidTime(formatDate(vo.getBcValidTime()));
						cardData.setChipsLessNo(vo.getChipsLessNo());
						cardData.setChipsLessPin(vo.getChipsLessPin());
						cardData.setBcNo(vo.getBcNo());					
						for(CardControl cardControl:cardControls){						
							if(cardData.getCardDataId().intValue()==cardControl.getCardDataId().intValue()){							
								// 业务流水表
								Business business = new Business();
								business.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
	//							business(agentName);//代理人姓名
	//							business.setAgentPaperNo(agentPaperNo);//代理人证件号码
	//							business.setAgentPapertype(agentPapertype);//代理人证件类型
	//							business.setAgentPhone(agentPhone);// 代理人联系电话
	//							business.setBatchNo(batchNo);//批次号
	//							business.setBusiNum(1);// 业务数量
								business.setCardControlId(cardControl.getCardControlId());// 卡控制号
								business.setCardpCode(cardData.getCardpCode());// 卡产品
	//							business.setCertNo(ce.getCertNo());// 凭证编号
	//							business.setCorpNo(corpNo);//单位编号 批量办理时使用
	//							business.setCustomerNo(p.getCustomerNo());// 客户编号
								business.setRemark("银卡制卡任务返回");// 备注
	//							business.setRptDate(rptDate);//轧帐日期
	//							business.setRptFlag(rptFlag);//轧帐标识
								business.setTellerNo(activeUser.getUserNo().toString());// 柜员号
								business.setTransAuthId("业务授权人编号001");// 业务授权人编号
								business.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
								business.setTransCode("交易代码");//
								business.setTransDate(new Date());//交易日期
								business.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况	
								businesses.add(business);
								//卡过程
								CardManage cme = new CardManage();
								String uuid=(UUID.randomUUID().toString()).replace("-", "");
								cme.setProcessId(uuid);
								cme.setBusinessNo(business.getBusinessNo());
								cme.setApplyBranch(activeUser.getBranchName());
								cme.setApplyBranchNo(activeUser.getBranchNo());
								cme.setApplyDate(now);
								cme.setApplyTellerNo(activeUser.getUserNo().toString());
								cme.setCardPosition(CardContants.CARD_POSITION_BANK);
								cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
								cme.setCardTaskNo(ct.getCardTaskNo());
								cme.setCardpCode(cardData.getCardpCode());
								cme.setCardTypecode(cardData.getCardTypecode());
								cme.setProcessCode(CardContants.CARD_PROC_OUT_STORAGE);
								cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_OUT_STORAGE));
								cme.setCitizenCardNo(vo.getCitizenCardNo());
								cme.setRemark("银行制卡返回");
								cme.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
								
								cardManages.add(cme);
								cardControl.setCardPosition(CardContants.CARD_POSITION_BANK);
								cardControl.setCardDate(formatDate(vo.getReturnDate()));
								cardControl.setClaimStatus(CardContants.CLAIM_STATUS_TOGIVE);
								cardControl.setCurrProcId(cme.getProcessId());
								break;
							}
						}
					}
				}
			
			}else if(CardContants.MAKE_CARD_RESULT_FAIL.equals(vo.getMakeCardResult())){
				logger.info("制卡失败,卡面号[{}]",vo.getCitizenCardNo());
			}	
		}
		bm.batchInsert(businesses);
		cmm.batchInsert(cardManages);
		cdm.batchUpdate(cardDatas);
		cardm.batchUpdate(cardControls);
		
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void returnMakeCardTaskByJS(List<String> makeCardInfos,List<String> cardInfos, ImportBankFileVo vv) throws ParseException ,Exception {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}	
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		//验证BTC文件和SQ文件记录数
		if(makeCardInfos.size()!=cardInfos.size()){
			throw new ApplicationException(ErrorCode.BTC_NO_SAME_SQ, "BTC File Num and SQ File Num is not same");
		}
		List<CardControl> cardControls=new ArrayList<>();//卡控制表
		List<CardData> cardDatas=new ArrayList<>();//卡数据表
		List<CardManage> cardManages=new ArrayList<>();//卡过程表
		List<Business> businesses=new ArrayList<>();//卡业务表
		List<Cert>certs=new ArrayList<>();//凭证表
		//存放银行卡和市民卡卡号绑定关系 key-市民卡号，value-银行卡号
		Map<String, String> map=new HashMap<>();
		for(String string:cardInfos){
			String[] array=StringUtils.splitPreserveAllTokens(string, "|");
			map.put(CommonUtil.AsciiStringToString(array[1]), array[0]);
		}
		Set<String> set=new HashSet<>(map.values());
		//验证BTC文件市民卡号和银行卡号是否重复
		if(map.size()<cardInfos.size()||set.size()<cardInfos.size()){
			throw new ApplicationException(ErrorCode.BTC_HAS_ERROR, "BTC File Has Same");
		}
		boolean b=true;
		String cardpCode=null;
		CardProdunctDefinition cpd=null;
		String copBankNo="";//合作银行编号
		Date now =new Date();
		int flag=1;
		CardTask ct = new CardTask();
		CardBatch cb = new CardBatch();
		Calendar cccc = Calendar.getInstance();
		for(String string:makeCardInfos){
			String [] info = StringUtils.splitPreserveAllTokens(string, "|");
			MakeCardFileReturnFileVo vo= new MakeCardFileReturnFileVo();
			vo.setFileName(info[0]);//制卡文件名--无后缀
			vo.setChipsLessNo(info[1]);//非接触芯片号
			vo.setChipsLessPin(info[2]);//非接片PIN
			vo.setCitizenCardNo(CommonUtil.AsciiStringToString(info[3]));//市民卡卡面号
			vo.setReturnDate(info[4]);//返回日期
			vo.setCardSeqNo(info[5]);//卡片序列号
			vo.setBcNo(map.get(CommonUtil.AsciiStringToString(info[3])));//银行卡号
			vo.setBcValidTime(info[7]);//银行卡有效期
			vo.setMakeCardResult(info[8]);//制卡结果
			vo.setMakeCardFailReason(info[9]);//制卡失败原因
//			vo.setOriMakeCardData(info[10]);//原卡数据暂时不用
			if(b){
				if("JS_BANK".equalsIgnoreCase(vv.getBank())){
					 copBankNo = CardContants.CARD_PUBLISHER_CODE_JS;
					 cardpCode=CardContants.CARD_P_CODE_JS;		 
				}
				// 今天+n天===预计领卡日期
				cccc.setTime(now);
				cccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());
				//上一条制卡批次
				CardBatch cardBatch = cbm.queryFirstCardBatch();
				//制卡批次号
				String batchMarkerNo = SequenceNumberUtil.generatorCardBatchKey(cardBatch);
				//保存制卡批次表
				cb.setBatchMarkerNo(batchMarkerNo);//制作批次号  yyMMdd+4位序号
				cb.setBackRecDate(now);//返回接收日期
				cb.setBackReceiver(activeUser.getUserNo().toString());//返回接收人
				//制卡商
				CooperationCompany ccom = cocm.queryCooperationCompanyByCompanyNo("102");
				cb.setDataReceiver(ccom.getCompanyType());// 数据接收方 就是 银行、制卡商
				cb.setDataSendDate(now);// 数据发送日期
				cb.setDataSender(activeUser.getUserNo().toString());// 数据发送人
				cb.setExportNum(1);// 导出次数
				cb.setFileName(vo.getFileName()+".txt");//文件名
				cb.setPerformType(CardContants.EXECUTION_MODE_OUTSOURCE);// 执行方式
				cb.setSupplierCode(ccom.getCompanyNo());//制卡厂商编号
				cbm.insert(cb);
				
				cpd=cpdm.queryCardPCode(cardpCode);
				
				String prevTaskNO=ctm.queryPreviousTaskNo();//上一个任务编号
				
				//任务表
				ct.setCardTaskNo(SequenceNumberUtil.getSequenceNumber(cpd.getCardpCode(),prevTaskNO));//制卡任务编号
				ct.setApplyBranchNo(activeUser.getBranchNo());// 申领网点编号
				ct.setApplyBranch(activeUser.getBranchName());// 申领网点名称
				ct.setBatchMarkerNo(cb.getBatchMarkerNo());//制作批次号
				ct.setCardpCode(cpd.getCardpCode());
				ct.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码
				ct.setCompanyNo("102");// 制卡厂商编号
				ct.setCorpCode(copBankNo);//单位代码
				ct.setCorpName(copBankNo.equals(CardContants.CARD_PUBLISHER_CODE_JS)==true?"建设银行":"潍坊银行");//单位名称
				ct.setIsUrgent("N");// 默认不加急  是否加急
				ct.setRecordNum(makeCardInfos.size());// 记录数量
				ct.setRemark("建设银行预制卡任务");// 备注
//				ct.setRollbackDate(rollbackDate);//回退日期
//				ct.setRollbackSn(rollbackSn);//回退日志流水号
//				ct.setRollbackStatus(rollbackStatus);//回退标志
				ct.setTaskName(vv.getFileName());// 任务名称---》建行任务名就是制卡返回文件名
				ct.setTaskPerType(CardContants.EXECUTION_MODE_OUTSOURCE);// 任务执行方式 外包 本地
				ct.setTasksGeneTime(now);// 任务产生时间
				ct.setTasksOperator(activeUser.getUserNo().toString());//
				ct.setTaskStatus(CardContants.BANK_RETURN);// 任务状态
				ct.setTaskType(CardContants.TASK_TYPE_NO_NAME_CARD);// 任务类型 1-记名卡任务																	// 2-不记名任务
				ctm.insert(ct);
				b=false;
			}
			
			//卡制卡成功
			if(CardContants.MAKE_CARD_RESULT_SUCCESS.equals(vo.getMakeCardResult())){
				//卡数据
				CardData cardData=new CardData();								   
//			    setCustomerNo(String customerNo);			
//			    setPhotoId(String photoId);
//			    setInitOrgCode(String initOrgCode); 
//			    setCityCode(String cityCode);			   
//			    setIndustryCode(String industryCode);		
//			    setChipsNo(String chipsNo);
//			    setChipsInno(String chipsInno);			   
//			    setChipsType(String chipsType);
//			    setChipsPin(String chipsPin);
//			    setChipsVersion(String chipsVersion);
//			    setChipsLessInno(String chipsLessInno)
//			    setChipsLessCtpe(String chipsLessCtpe);
//			    setChipsLessVer(String chipsLessVer);
//			    setChipsLessType(String chipsLessType);	 
//			    setTwoTraInfo(String twoTraInfo) ;
//			    setThreeTraInfo(String threeTraInfo) ;
//			    setServerPass(String serverPass);
//			    setBarcode(String barcode);
//			    setChipsEdate(Date chipsEdate)
//			    setChipsEflag(String chipsEflag)
//			    setChipsLessEd(Date chipsLessEd)
//			    setChipsLessEf(String chipsLessEf)
//			    setTestFlag(String testFlag)
//			    setOriCardSeqNo(String oriCardSeqNo)
//			    setChcOriCitizenNo(String chcOriCitizenNo)
//			    setChipsLessDate(Date chipsLessDate)
//			    setAppTypeEf(String appTypeEf)
//			    setAppSerialNo(String appSerialNo)
//			    setVersionNo(String versionNo);			  
//			    setCardConsumer(String cardConsumer);
//			    cardData.setCardSeqNo(String cardSeqNo); 									
				cardData.setCardpCode(cardpCode);
				cardData.setCitizenCardNo(vo.getCitizenCardNo());
				cardData.setCardTypecode(cpd.getCardTypeCode());
				cardData.setCardValidTime(CommonUtil.willDate(now, cpd.getCardValidTime()));
				cardData.setCopBankNo(copBankNo);
				cardData.setCardSeqNo(vo.getCardSeqNo());
				//cardData.setBcValidTime(formatDate(vo.getBcValidTime()));//银行有效期
				cardData.setChipsLessNo(vo.getChipsLessNo());
				cardData.setChipsLessPin(vo.getChipsLessPin());
				cardData.setBcNo(vo.getBcNo());
				cardData.setCardPhysicalType("0");//标准IC卡
				cardData.setFlag(flag);
				cardDatas.add(cardData);
				
				// 业务流水表
				Business business = new Business();
				business.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
//				business(agentName);//代理人姓名
//				business.setAgentPaperNo(agentPaperNo);//代理人证件号码
//				business.setAgentPapertype(agentPapertype);//代理人证件类型
//				business.setAgentPhone(agentPhone);// 代理人联系电话
//				business.setBatchNo(batchNo);//批次号
//				business.setBusiNum(1);// 业务数量
//				business.setCardControlId(cc.getCardControlId());// 卡控制号
				business.setCardpCode(cardData.getCardpCode());// 卡产品
//				business.setCertNo(ce.getCertNo());// 凭证编号
//				business.setCorpNo(corpNo);//单位编号 批量办理时使用
//				business.setCustomerNo(p.getCustomerNo());// 客户编号
				business.setRemark("建设银卡制卡任务返回");// 备注
//				business.setRptDate(rptDate);//轧帐日期
//				business.setRptFlag(rptFlag);//轧帐标识
				business.setTellerNo(activeUser.getUserNo().toString());// 柜员号
				business.setTransAuthId("业务授权人编号001");// 业务授权人编号
				business.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
				business.setTransCode("交易代码");//
				business.setTransDate(new Date());//交易日期
				business.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况	
				business.setFlag(flag);
				
				//卡过程
				CardManage cme = new CardManage();
				String uuid=(UUID.randomUUID().toString()).replace("-", "");
				cme.setProcessId(uuid);
				cme.setBusinessNo(business.getBusinessNo());
				cme.setApplyBranch(activeUser.getBranchName());
				cme.setApplyBranchNo(activeUser.getBranchNo());
				cme.setApplyDate(now);
				cme.setApplyTellerNo(activeUser.getUserNo().toString());
				cme.setCardPosition(CardContants.CARD_POSITION_BANK);
				cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
				cme.setCardTaskNo(ct.getCardTaskNo());
				cme.setCardpCode(cardpCode);
				cme.setCardTypecode(cpd.getCardTypeCode());
				cme.setProcessCode(CardContants.CARD_PROC_OUT_STORAGE);
				cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_OUT_STORAGE));
				cme.setCitizenCardNo(vo.getCitizenCardNo());
				cme.setRemark("建设银行制卡返回");
				cme.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
				cardManages.add(cme);
				
//				 凭证表
				Cert ce = new Cert();
				ce.setCertNo(SequenceNumberUtil.generatorCertNo());
				ce.setBranch(activeUser.getBranchName());// 网点名称
				ce.setBranchNo(activeUser.getBranchNo());// 网点编号
				ce.setBusinessNo(business.getBusinessNo());//业务流水号
//				ce.setCardControlId(cc.getCardControlId());
				ce.setCertType(CardContants.SINGLE_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请
																// 3 出库配送 4 单笔发卡 5
																// 批量发卡
				ce.setCardpCode(cardpCode);// 卡产品代码
				ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
															// 3.非记名衍生卡
				ce.setCorpCode(copBankNo);// 单位编号id
				ce.setCorpName(copBankNo.equals(CardContants.CARD_PUBLISHER_CODE_JS)==true?"建设银行":"潍坊银行");// 单位名称
				ce.setCrtDate(now);
				ce.setCrtOperator(activeUser.getUserNo().toString());
				ce.setData("银行联名卡申请凭证 ");// 打印凭证数据
				ce.setLastDate(now);
				ce.setLastOperator(activeUser.getUserNo().toString());
//				ce.setName(p.getCustomerName());// 持卡人姓名
//				ce.setPaperNo(p.getPaperNo());
//				ce.setPaperType(p.getPaperType());
				ce.setPrintCount(0);// 打印次数
//				ce.setTransCode(transCode);//交易代码
				ce.setFlag(flag);	
				certs.add(ce);
				business.setCertNo(ce.getCertNo());
				businesses.add(business);
				//卡控制表
				CardControl cc = new  CardControl();
				cc.setClaimStatus(CardContants.CLAIM_STATUS_TOGIVE);
				cc.setCardStatus(CardContants.CARD_STATE_DISABLED);
				cc.setCurrProcId(cme.getProcessId());// 申领状态：制卡
				cc.setCardPosition(CardContants.CARD_POSITION_BANK);// 卡位置：制卡间
				cc.setCardTaskNo(ct.getCardTaskNo());
				cc.setApplyDate(cccc.getTime());// 预计林卡日期
				cc.setCardDate(now);//制卡日期
				cc.setCrtDate(now);
				cc.setCrtOperator(activeUser.getUserNo().toString());
				cc.setLastDate(now);
				cc.setLastOperator(activeUser.getUserNo().toString());
				cc.setDmgFlag(CardContants.CARD_UNDAMAGED);	// 卡损坏状况
															// 0-未损坏，1-非人为损坏，2-人为损坏
				// cc.setLogoutDate(logoutDate);//注销日期
				// cc.setLogoutReason(logoutReason);//注销原因
				// cc.setReleaseDate(ccc.getTime());//发卡日期
				cc.setRemark("银行联名卡卡控制表");
				cc.setApplyType(CardContants.APPLY_TYPE_FIRST);
				cc.setFlag(flag);
				cardControls.add(cc);
				
				
			
			}else if(CardContants.MAKE_CARD_RESULT_FAIL.equals(vo.getMakeCardResult())){
				logger.info("制卡失败,卡面号[{}]",vo.getCitizenCardNo());
			}
			flag++;
		}
		//更新卡号段使用情况
		Set<String> set2=map.keySet();
		List<String> cardNos=new ArrayList<>(set2);
		Collections.sort(cardNos,new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				int a=Integer.parseInt(o1.substring(5));
				int b=Integer.parseInt(o2.substring(5));
				if(a<b){
					return -1;
				}else{
					return 1;
				}
				
			}
		});
		
		int startSegmentNo=Integer.parseInt(cardNos.get(0).substring(5));
		int endSegmentNo=Integer.parseInt(cardNos.get(cardNos.size()-1).substring(5));
		//未使用完的卡号段
		List<CardNoGenerated> cardNoGenerateds= cngm.queryAllRecordByCardpCode(cardpCode);		
	//验证银行的卡号段是否已经使用
		//所有卡号段使用明细
		List<CardNoUseDetail> details=cndm.queryAllByCardpCode(cardpCode);
		if(details!=null){
			for(CardNoUseDetail detail :details){
				int currEndSegmentNo=Integer.valueOf(detail.getEndSegmentNo());
	    		int currStartSegmentNo=Integer.valueOf(detail.getStartSegmentNo());
				if(startSegmentNo>=currStartSegmentNo&&startSegmentNo<=currEndSegmentNo){
					throw new ApplicationException(ErrorCode.CAERD_SEGMENT_USEING,"card_segment_useing");
				}
				if(endSegmentNo>=currStartSegmentNo&&endSegmentNo<=currEndSegmentNo){
					throw new ApplicationException(ErrorCode.CAERD_SEGMENT_USEING,"card_segment_useing");
				}
			}
		}
		//批量修改
		cdm.batchInsert(cardDatas);
		cmm.batchInsert(cardManages);
		for(CardData cd:cardDatas){
			for(CardControl cc:cardControls){
				if(cc.getFlag()==cd.getFlag()){
					cc.setCardDataId(cd.getCardDataId());
					break;
				}
			}
		}
		cardm.batchInsert(cardControls);
		for(Business bb:businesses){
			for(CardControl cc:cardControls){
				if(cc.getFlag()==bb.getFlag()){
					bb.setCardControlId(cc.getCardControlId());
				}
			}
		}
		for(Cert cert:certs){
			for(CardControl c:cardControls){
				if(c.getFlag()==cert.getFlag()){
					cert.setCardControlId(c.getCardControlId());
				}
			}
		}
		bm.batchInsert(businesses);
		cem.batchInsert(certs);
		updateCardNoUse(startSegmentNo, endSegmentNo, cardNoGenerateds, cardpCode);
		
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void returnActivateCardInfo(List<String> list, ImportBankFileVo vo) throws ParseException {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		Date currentTime=new Date();
		//卡号集合
		List<String> citizenCardNos=new ArrayList<>();
		List<BankProvidePersonalVo>vos=new ArrayList<>();
		//控制表集合
		List<CardControl> cardControls=new ArrayList<>();
		//数据表集合
		List<CardData> cardDatas=new ArrayList<>();
		//个人信息表集合
		List<Personal> personals=new ArrayList<>();
		//卡过程表集合
		List<CardManage>cardManages=new ArrayList<>();
		//业务流水表集合
		List<Business> businesses=new ArrayList<>();
		//凭证表集合
		List<Cert> certs=new ArrayList<>();
		//默认开通公交
		AppKind ak = akm.queryAppKindByAppFalg(AppContants.APP_FLAG_TRANSIT);
		for(String str:list){
			String [] info=StringUtils.splitPreserveAllTokens(str,"|");
			BankProvidePersonalVo personalVo=new BankProvidePersonalVo();
			personalVo.setPaperType(info[0]);
			personalVo.setPaperNo(info[1]);
			personalVo.setCustomerName(info[2]);
			if(info[3].contains("男")||info[3].contains("1")){
				personalVo.setGender(CardContants.GENDER_MALE);
			}else if(info[3].contains("女")||info[3].contains("2")){
				personalVo.setGender(CardContants.GENDER_FEMALE);
			}
			personalVo.setNationality(info[4]);
			personalVo.setBirthday(info[5]);
			personalVo.setPrAddrDetailedInfo(info[6]);//户籍地址
			personalVo.setMobile(info[7]);
			personalVo.setCurAddrDetailedInfo(info[8]);//家庭地址
			personalVo.setCurPostalcode(info[9]);//邮编
//			personalVo.setParentsLink(info[10]);//家长联系方式（文件去除）
//			personalVo.setSchoolName(info[11]);//所在学校（文件去除）
			if(info[10].length()==12){
				personalVo.setCitizenCardNo(info[10]);//建设银行传过来市民卡号
			}else{
				personalVo.setBcNo(info[10]);//潍坊银行传过来银行卡号
				personalVo.setCitizenCardNo(cdm.queryCardDataByBcNo(personalVo.getBcNo()).getCitizenCardNo());
			}
			
			//收集卡号
			citizenCardNos.add(personalVo.getCitizenCardNo());
			//新增个人信息
			Personal personal=new Personal();
			personal.setCustomerNo(UUID.randomUUID().toString().replace("-", ""));
			personal.setPaperType(personalVo.getPaperType());
			personal.setPaperNo(personalVo.getPaperNo());
			personal.setCustomerName(personalVo.getCustomerName());
			personal.setGender(personalVo.getGender());
			personal.setNationality(personalVo.getNationality());
			personal.setBirthday(formatDate(personalVo.getBirthday()));
			personal.setPrAddrDetailedInfo(personalVo.getPrAddrDetailedInfo());
			personal.setMobile(personalVo.getMobile());
			personal.setCurAddrDetailedInfo(personalVo.getCurAddrDetailedInfo());
			personal.setCurPostalcode(personalVo.getCurPostalcode());
			personal.setParentsLink(personalVo.getParentsLink());
			personal.setSchoolName(personalVo.getSchoolName());
			personals.add(personal);
			personalVo.setCustomerNo(personal.getCustomerNo());
			vos.add(personalVo);
		}
		//查询要修改的卡数据和控制集合
		cardDatas=cdm.queryCardDataByCitizenCardNoList(citizenCardNos);
		cardControls=cardm.queryCardControlByCitizenNoList(citizenCardNos);
		for(CardControl cardControl:cardControls){
			CardData cardData=null;
			Business bu=null;
			Cert cert=null;
			for(CardData cd:cardDatas){
				if(cd.getCardDataId().equals(cardControl.getCardDataId())){
					for(BankProvidePersonalVo bvo:vos){
						if(bvo.getCitizenCardNo().equals(cd.getCitizenCardNo())){
							cd.setCustomerNo(bvo.getCustomerNo());
							
							cert = new Cert();
							cert.setCertNo(SequenceNumberUtil.generatorCertNo());
							cert.setCertType(CardContants.SINGLE_CARD);
							cert.setCardpCode(cd.getCardpCode());
							cert.setCardTypecode(cd.getCardTypecode());
							cert.setName(bvo.getCustomerName());
							cert.setPaperNo(bvo.getPaperNo());
							cert.setPaperType(bvo.getPaperType());
							cert.setBranch(activeUser.getBranchName());
							cert.setBranchNo(activeUser.getBranchNo());
							cert.setCardControlId(cardControl.getCardControlId());
							cert.setData("银行卡发卡");
							cert.setCrtDate(currentTime);
							cert.setCrtOperator(activeUser.getUserNo().toString());
							cert.setLastOperator(activeUser.getUserNo().toString());
							cert.setLastDate(currentTime);
							
							
							bu = new Business();
							bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
							bu.setCustomerNo(cd.getCustomerNo());
							bu.setCardControlId(cardControl.getCardControlId());
							bu.setTellerNo(activeUser.getUserNo().toString());
							// bu.setTransDate(new Date());// 交易日期
							bu.setSeqStatus(CardContants.LSZT_NORMAL);
							bu.setRemark("银行联名卡首次发卡");
							bu.setCertNo(cert.getCertNo());
							businesses.add(bu);
							cert.setBusinessNo(bu.getBusinessNo());
							certs.add(cert);
							
							//主账号
							MainAccountPersonal m = mapm.queryMainAccountPersonalByCustomerNo(cd.getCustomerNo());
							if (m == null) {
								m = new MainAccountPersonal();
								m.setAccountName(bvo.getCustomerName());
								m.setCustomerNo(cd.getCustomerNo());
								m.setAccoBranchNo(activeUser.getBranchNo());
								m.setAccoTellerNo(activeUser.getUserNo().toString());
								m.setAccoDate(currentTime);
								m.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);
								mapm.insert(m);
							}
							
							// 开通应用 默认开通 -公交应用
							AppOpenReg ao = new AppOpenReg();
							ao.setCitizenCardNo(cd.getCitizenCardNo());
							ao.setAppType(String.valueOf(ak.getAppType()));
							ao.setOpenDate(currentTime);
							if (ak.getValidMonthNum() != null) {

								ao.setIsValid(AppContants.APP_ISVALID); // 月份计算
								ao.setValidBegin(currentTime);
								ao.setValidEnd(CommonUtil.willDate(currentTime, ak.getValidMonthNum()));

							} else {
								ao.setIsValid(AppContants.APP_NOVALID); // 月份计算
							}

							// ao.setStopDate(a.getStopDate());//停用日期
							// ao.setRetrieveDate(a.getRetrieveDate());//恢复日期
							ao.setAppStatus(AppContants.APP_STATUS_OPEN);// 应用状态
							ao.setRemark("银行发卡，默认开通公交3F01应用");
							ao.setIsDeposit(AccountContants.IS_DEPOSIT_NO);//默认未退款
							ao.setCrtOperator(activeUser.getUserNo().toString());
							ao.setCrtDate(currentTime);
							ao.setLastOperator(activeUser.getUserNo().toString());
							ao.setLastDate(currentTime);
							aorm.insert(ao);

							// 钱包1
							SubaccountPersonal cardWallet = new SubaccountPersonal();
							cardWallet.setAccoBranchNo(activeUser.getBranchNo());// 开户网点编号
							cardWallet.setAccoDate(currentTime);// 开户日期
							cardWallet.setAccoTellerNo(activeUser.getUserNo().toString());// 开户柜员号
							cardWallet.setAccountName(bvo.getCustomerName());// 户名
							cardWallet.setAccountPw(AccountContants.CARD_WALLET_INT_PASSWORD);// 账户密码
							// cardWallet.setAccountSign(accountSign);//帐户标识
							cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);//帐号状态
							cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_BANKBOOK);// 所属钱包类型id
																									// 01-电子存折
																									// 02-电子钱包
							cardWallet.setAppFlag(ak.getAppFlag());// 应用标识 默认开通公交
							// cardWallet.setCardSeqNo(cappFlagardSeqNo);//卡片序列号
							cardWallet.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
							cardWallet.setCityCode(CardContants.CITY_CODE);// 城市代码
							// cardWallet.setClsDate(clsDate);//销户日期
							// cardWallet.setClsTellerNo(clsTellerNo);//销户柜员号
							cardWallet.setCrdBalance(new BigDecimal(0));// 卡面余额
							// cardWallet.setCrdNo(crdNo);//卡内号
							cardWallet.setCurrCount(0);// 当前计数器值
							cardWallet.setCustomerNo(cd.getCustomerNo());// 客户编号
							cardWallet.setErrorDegree((short) 0);// 输错次数
							cardWallet.setFreezeAmount(new BigDecimal(0));// 冻结金额
							// cardWallet.setFreezeDate(freezeDate);//冻结日期
							cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);// 冻结标志
							// cardWallet.setInaccEndDate(inaccEndDate);//入账截止日期
							// cardWallet.setInaccEndStatus(inaccEndStatus);// 入账截止状态
							// cardWallet.setLastTransDate(lastTransDate);//最后交易日
							// cardWallet.setLastTransNo(lastTransNo);//最后交易流水号
							// cardWallet.setLossDate(lossDate);//挂失日期
							cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);// 挂失状态
							cardWallet.setMainaccountNo(m.getMainaccountNo());// 主帐户号
							cardWallet.setMaxCount(0);// 最大计数器值
							// cardWallet.setOnlCurrCount(onlCurrCount);//联机交易计数器
							// cardWallet.setOnlTxnDt(onlTxnDt);//最后联机交易时间
							cardWallet.setPasswordStatus(null);// 密码标志
							cardWallet.setProductNumber(0);// 积数
							cardWallet.setRemark("售卡，开通应用钱包");
							cardWallet.setSumJe(0);// 消费积分
							cardWallet.setTotalBalance(new BigDecimal(0));// 账面余额
							cardWallet.setTotalConsumeAmt(new BigDecimal(0));// 累计消费金额
							cardWallet.setTotalConsumeCnt(0);// 累计消费笔数
							cardWallet.setTotalExchangeAmt(new BigDecimal(0));// 累计圈存金额
							cardWallet.setTotalExchangeCnt(0);// 累计圈存笔数
							cardWallet.setTotalReloadAmt(new BigDecimal(0));// 累计充值金额
							cardWallet.setTotalReloadCnt(0);// 累计充值笔数
							cardWallet.setValidDate(null);// 有效期

							spm.insert(cardWallet);

							// 钱包2
							cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET);// 钱包类型
							spm.insert(cardWallet);
							
							break;
						}
					}
					cardData=cd;
					break;
				}
			}
			
			CardManage cardManage = new CardManage();
			cardManage.setProcessId(UUID.randomUUID().toString().replace("-", ""));
			cardManage.setApplyBranch(activeUser.getBranchName());
			cardManage.setApplyBranchNo(activeUser.getBranchNo());
			cardManage.setProcessCode(CardContants.CARD_PROC_RETRIEVE);
			cardManage.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
			cardManage.setApplyTellerNo(activeUser.getUserNo().toString());
			cardManage.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
			cardManage.setCardpCode(cardData.getCardpCode());
			cardManage.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			cardManage.setCardStatus(CardContants.CARD_STATE_NORMAL);
			cardManage.setCardTypecode(cardData.getCardTypecode());
			cardManage.setCustomerNo(cardData.getCustomerNo());
			cardManage.setRemark("银行联名卡发卡");
			cardManage.setApplyDate(currentTime);
			cardManage.setCitizenCardNo(cardData.getCitizenCardNo());
			cardManage.setBusinessNo(bu.getBusinessNo());
			cardManage.setCertNo(cert.getCertNo());
			cardManages.add(cardManage);
			
			cardControl.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			cardControl.setCardStatus(CardContants.CARD_STATE_NORMAL);
			cardControl.setClaimStatus(CardContants.CLAIM_STATUS_GIVEN);
			// cc.setApplyDate(currentTime);
			cardControl.setLastDate(currentTime);
			cardControl.setReleaseDate(currentTime);
			cardControl.setLastOperator(activeUser.getUserNo().toString());
			cardControl.setCurrProcId(cardManage.getProcessId());
			cardControl.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
			cardControl.setRemark("银行卡联名卡发卡");
	
		}
		cardm.batchUpdate(cardControls);
		cdm.batchUpdate(cardDatas);
		bm.batchInsert(businesses);
		cmm.batchInsert(cardManages);
		pm.batchInsert(personals);
		cem.batchInsert(certs);			
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateLossCancleStatus(List<String>list,ImportBankFileVo vv) throws ApplicationException{
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		Date now = new Date();
		//卡号列表
		List<String>cardNos=new ArrayList<>();
		//文件数据
		List<BankLossCancleVo> bankLossCancleVos=new ArrayList<>();
		
		List<CardControl>cardControls=new ArrayList<>();
		List<CardData> cardDatas=new ArrayList<>();
		List<Cert> certs=new ArrayList<>();
		List<CardManage> cardManages=new ArrayList<>();
		List<Business>businesses=new ArrayList<>();
		List<Personal> personals=new ArrayList<>();
		for(String str:list){
			String [] info = StringUtils.splitPreserveAllTokens(str, "|");
			BankLossCancleVo vo = new BankLossCancleVo();
			vo.setBussinessType(info[0]);
			vo.setBcNo(info[1]);
			if(info[2]==""){//市民卡号为空
				CardData cardData=cdm.queryCardDataByBcNo(vo.getBcNo());
				if(cardData==null){
					throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "导入文件异常，卡号错误，无此人信息");
				}
				vo.setCitizenCardNo(cardData.getCitizenCardNo());
			}else{
				vo.setCitizenCardNo(info[2]);
			}
			
			cardNos.add(vo.getCitizenCardNo());
			bankLossCancleVos.add(vo);
		}
		//获取卡相关数据列表
		cardControls=cardm.queryCardControlByCitizenNoList(cardNos);
		cardDatas=cdm.queryCardDataByCitizenCardNoList(cardNos);
		personals=pm.getPersonalByCitizenCardNoList(cardNos);
		//根据文件内容执行相关业务流程
		for(BankLossCancleVo vo:bankLossCancleVos){	
			//找出此卡卡数据信息
			for(CardData c:cardDatas){
				if(c.getCitizenCardNo().equals(vo.getCitizenCardNo())&&c.getBcNo().equals(vo.getBcNo())){
					//找出此卡相关的个人信息
					Personal p=null;
					for(Personal personal:personals){
						if(personal.getCustomerNo().equals(c.getCustomerNo())){
							p=personal;
							break;
						}
					}
					//找出此卡控制表信息
					for(CardControl cc:cardControls){
						if(cc.getCardDataId().intValue()==c.getCardDataId().intValue()){
							//非解挂业务
							if(!CardContants.STANDARD_CARD_BUSSINESS_UNLOSS.equals(vo.getBussinessType())){

								//联名卡挂失
								if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType())){
									cc.setCardStatus(CardContants.CARD_STATE_OFFICIAL_LOSS);// 正式挂失
									cc.setIsRead(CardContants.CARD_NO_READ);//挂失 卡不可讀
									cc.setLossDate(now);
									cc.setLossReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
									List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNo(vo.getCitizenCardNo());
									for(SubaccountPersonal cardWallet:lsp){
										cardWallet.setLossDate(now);
										cardWallet.setLossStatus(CardContants.CARD_STATE_OFFICIAL_LOSS);
										cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_FROZEN);
										cardWallet.setFreezeAmount(cardWallet.getTotalBalance());
										cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_WHOLE);
										cardWallet.setFreezeDate(now);
										cardWallet.setRemark(AppContants.APP_STATUS_CLOSE_LOSSCARD);
										spm.update(cardWallet);
									}
									//联名卡有卡注销
								}else if(CardContants.STANDARD_CARD_BUSSINESS_HAS_CARD_CANCLE.equals(vo.getBussinessType())){
									cc.setCardStatus(CardContants.CARD_STATE_CANCELLATION_HAS_CARD);//注销
									cc.setIsRead(CardContants.CARD_NO_READ);
									cc.setClaimStatus(CardContants.CLAIM_STATUS_CANCEL);
									cc.setCardPosition(CardContants.CARD_POSITION_BANK);
									cc.setLogoutDate(now);
									cc.setLogoutReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
									List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNo(vo.getCitizenCardNo());

									for(SubaccountPersonal cardWallet:lsp){
										cardWallet.setClsDate(now);
										cardWallet.setClsTellerNo(activeUser.getUserNo().toString());
										cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_CANCEL_ACCOUNT);
										spm.update(cardWallet);
									}
									////联名卡无卡注销
								}else if(CardContants.STANDARD_CARD_BUSSINESS_NO_CARD_CANCLE.equals(vo.getBussinessType())){
									cc.setCardStatus(CardContants.CARD_STATE_CANCELLATION_NO_CARD);// 注销
									cc.setIsRead(CardContants.CARD_NO_READ);// 卡不可讀
									cc.setClaimStatus(CardContants.CLAIM_STATUS_CANCEL);
									cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
									cc.setLogoutDate(now);
									cc.setLogoutReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
									List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNo(vo.getCitizenCardNo());
									for(SubaccountPersonal cardWallet:lsp){
										cardWallet.setClsDate(now);
										cardWallet.setClsTellerNo(activeUser.getUserNo().toString());
										cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_CANCEL_ACCOUNT);
										spm.update(cardWallet);
									}
								}
								cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_INNER);// 黑名单标识
								cc.setLastDate(now);
								cc.setLastOperator(activeUser.getUserNo().toString());
								
								//关闭应用
								List<AppOpenReg> la = aorm.queryAppOpenRegByCitizenCardNo(vo.getCitizenCardNo(),AppContants.APP_STATUS_OPEN);//该卡的所有应用
								for(AppOpenReg aor:la){
									if(AppContants.APP_STATUS_OPEN.equals(aor.getAppStatus())){
										aor.setAppStatus(AppContants.APP_STATUS_CLOSE);
										aor.setRemark(AppContants.APP_STATUS_CLOSE_LOSSCARD);
										aor.setLastDate(now);
										aor.setLastOperator(activeUser.getUserNo().toString());
										aorm.update(aor);
									}
								}
								
								//新增凭证
								Cert ce = new Cert();
								ce.setCertNo(SequenceNumberUtil.generatorCertNo());
								if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType())){
									ce.setCertType(CardContants.OFFICIAL_LOSS);
									ce.setData("联名卡挂失");
								}													
								else{
									ce.setCertType(CardContants.BACK_CARD_REGISTRATION);
									ce.setData("联名卡注销");
								}									
								ce.setCardpCode(c.getCardpCode());								
								ce.setCardTypecode(c.getCardTypecode());
								ce.setName(p.getCustomerName());
								ce.setPaperNo(p.getPaperNo());
								ce.setPaperType(p.getPaperType());
								ce.setBranch(activeUser.getBranchName());
								ce.setBranchNo(activeUser.getBranchNo());
								ce.setCardControlId(cc.getCardControlId());
								ce.setCrtDate(now);
								ce.setCrtOperator(activeUser.getUserNo().toString());
								ce.setLastOperator(activeUser.getUserNo().toString());
								ce.setLastDate(now);
								
								
								Business bu = new Business();
								bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
								bu.setCustomerNo(c.getCustomerNo());
								bu.setCardControlId(cc.getCardControlId());
								bu.setTellerNo(activeUser.getUserNo().toString());
								// bu.setTransDate(new Date());// 交易日期
								bu.setSeqStatus(CardContants.LSZT_NORMAL);
								if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType()))
									bu.setRemark("银行联名卡挂失");
								else 
									bu.setRemark("银行联名卡注销");
								
								bu.setCertNo(ce.getCertNo());
								businesses.add(bu);
								ce.setBusinessNo(bu.getBusinessNo());
								certs.add(ce);
								CardManage cardManage = new CardManage();
								cardManage.setProcessId(UUID.randomUUID().toString().replace("-", ""));
								cardManage.setApplyBranch(activeUser.getBranchName());
								cardManage.setApplyBranchNo(activeUser.getBranchNo());
								cardManage.setProcessCode(CardContants.CARD_PROC_WASTE_STORAGE);
								cardManage.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_WASTE_STORAGE));
								cardManage.setApplyTellerNo(activeUser.getUserNo().toString());
								cardManage.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
								cardManage.setCardpCode(c.getCardpCode());		
								cardManage.setCardStatus(cc.getCardStatus());
								cardManage.setCardTypecode(c.getCardTypecode());
								cardManage.setCustomerNo(c.getCustomerNo());
								if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType())){
									cardManage.setRemark("银行联名卡挂失");
									cardManage.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
								}	
								else{
									cardManage.setRemark("银行联名卡注销");
									cardManage.setCardPosition(CardContants.CARD_POSITION_BANK);
								}	
								cardManage.setApplyDate(now);
								cardManage.setCitizenCardNo(c.getCitizenCardNo());
								cardManage.setBusinessNo(bu.getBusinessNo());
								cardManage.setCertNo(ce.getCertNo());
								cardManages.add(cardManage);
								
								cc.setCurrProcId(cardManage.getProcessId());
								
								//黑名单
								BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(vo.getCitizenCardNo());
								Calendar calendar = Calendar.getInstance();
								calendar.setTime(now);
								calendar.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
								if (bb == null) {
									bb = new BlackListGen();
									bb.setCitizenCardNo(vo.getCitizenCardNo());
									bb.setCityCode(CardContants.CITY_CODE);
									// bb.setAppType(appType);//置黑应用类型
									// bb.setChipsInno(chipsInno);//接触卡内号
									// bb.setChipsLessInno(chipsLessInno);//非接卡内号
									// bb.setChipsLessNo(chipsLessNo);//非接芯片号
									// bb.setChipsNo(chipsNo);//接触芯片号

									bb.setBlCount(1);// 进黑名单次数
									bb.setBlReCount(0);// 解除黑名单次数
									//bb.setBlReReason(blReReason);//解除黑名单原因
									//bb.setRelieveDate(relieveDate);//解除日期	
									if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType()))
										bb.setBlReason(BlackListContants.BL_REASON_OFFICIAL_LOSS );
									else
										bb.setBlReason(BlackListContants.BL_REASON_BACK_CARD_CANCELLATION );
									
									bb.setBlReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));	
									bb.setAvailDate(calendar.getTime());// 生效日期
									bb.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式
									bb.setReleaseSys(BlackListContants.BL_PUBLISHING_SYSTEM_LIST_ALl);// 发布系统列表
									bb.setCurStatus(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 当前状态
									bb.setLastBlRcDate(now);// 最后更新日期
									blgm.insert(bb);

								} else {
									bb.setBlCount(bb.getBlCount() + 1);
//									bb.setBlReReason(null);// 解除黑名单原因
//									bb.setRelieveDate(null);// 解除日期
									if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType()))
										bb.setBlReason(BlackListContants.BL_REASON_OFFICIAL_LOSS );
									else
										bb.setBlReason(BlackListContants.BL_REASON_BACK_CARD_CANCELLATION );
									bb.setAvailDate(calendar.getTime());// 生效日期
									bb.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式
									bb.setReleaseSys(BlackListContants.BL_PUBLISHING_SYSTEM_LIST_ALl);// 发布系统列表
									bb.setCurStatus(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 当前状态
									bb.setLastBlRcDate(now);// 最后更新日期
									blgm.update(bb);

								}
								//黑名单记录表
								BlackListRc blr = new BlackListRc();
								// blr.setAppType(appType);//置黑应用类型
								blr.setCitizenCardNo(vo.getCitizenCardNo());// 市民卡号
								blr.setRegisterType(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 登记类型																			// 2.解除
								blr.setAvailDate(calendar.getTime());// 生效日期
								// blr.setRelieveDate(relieveDate);//解除日期
								blr.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式 0-系统;																					// 1-手工
								if(CardContants.STANDARD_CARD_BUSSINESS_LOSS.equals(vo.getBussinessType()))
									blr.setBlReason(BlackListContants.BL_REASON_OFFICIAL_LOSS );
								else
									blr.setBlReason(BlackListContants.BL_REASON_BACK_CARD_CANCELLATION );
								// blr.setBlReReason(blReReason);//解除黑名单原因
								// blr.setCriticalLevel(criticalLevel);//严重级别 0-9, 严重级别由低至高.
								blr.setBlSource(BlackListContants.BL_SOURCE_ALL);// 黑名单来源
								// blr.setReleaseSys(releaseSys);//下发系统
								// blr.setTransCode(transCode);//交易代码
								blr.setBusinessNo(bu.getBusinessNo());// 综合业务流水号
								// blr.setDoubtTrNo(doubtTrNo);/可疑交易流水号
								// blr.setssLockTrNo(lockTrNo);//锁卡交易流水号
								blr.setRemark(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
								blr.setOperDate(now);
								blr.setOpNetworkNo(activeUser.getBranchNo());
								blr.setTellerNo(activeUser.getUserNo().toString());
								blrm.insert(blr);
							}else{
								//解挂业务
								cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
								cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
								cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
								
								//新增凭证
								Cert ce = new Cert();
								ce.setCertNo(SequenceNumberUtil.generatorCertNo());					
								ce.setCertType(CardContants.CARD_UNBIND);
								ce.setCardpCode(c.getCardpCode());
								ce.setCardTypecode(c.getCardTypecode());
								ce.setName(p.getCustomerName());
								ce.setPaperNo(p.getPaperNo());
								ce.setPaperType(p.getPaperType());
								ce.setBranch(activeUser.getBranchName());
								ce.setBranchNo(activeUser.getBranchNo());
								ce.setCardControlId(cc.getCardControlId());
								ce.setCrtDate(now);
								ce.setCrtOperator(activeUser.getUserNo().toString());
								ce.setLastOperator(activeUser.getUserNo().toString());
								ce.setLastDate(now);
								ce.setData("银行卡解挂");
								
								Business bu = new Business();
								bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
								bu.setCustomerNo(c.getCustomerNo());
								bu.setCardControlId(cc.getCardControlId());
								bu.setTellerNo(activeUser.getUserNo().toString());
								// bu.setTransDate(new Date());// 交易日期
								bu.setSeqStatus(CardContants.LSZT_NORMAL);
								bu.setRemark("银行联名卡解挂");
								bu.setCertNo(ce.getCertNo());
								ce.setBusinessNo(bu.getBusinessNo());
								certs.add(ce);
								businesses.add(bu);
								
								CardManage cardManage = new CardManage();
								cardManage.setProcessId(UUID.randomUUID().toString().replace("-", ""));
								cardManage.setApplyBranch(activeUser.getBranchName());
								cardManage.setApplyBranchNo(activeUser.getBranchNo());
								//cardManage.setProcessCode(CardContants.CARD_PROC_WASTE_STORAGE);
								//cardManage.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
								cardManage.setApplyTellerNo(activeUser.getUserNo().toString());
								cardManage.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
								cardManage.setCardpCode(c.getCardpCode());							
								cardManage.setCardStatus(CardContants.CARD_STATE_NORMAL);
								cardManage.setCardTypecode(c.getCardTypecode());
								cardManage.setCustomerNo(c.getCustomerNo());						
								cardManage.setRemark("银行联名卡解挂");
								cardManage.setCardPosition(CardContants.CARD_POSITION_BANK);									
								cardManage.setApplyDate(now);
								cardManage.setCitizenCardNo(c.getCitizenCardNo());
								cardManage.setBusinessNo(bu.getBusinessNo());
								cardManage.setCertNo(ce.getCertNo());
								cardManages.add(cardManage);
								
								cc.setCurrProcId(cardManage.getProcessId());
								//恢复账户
								List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNoAndRemark(vo.getCitizenCardNo(),AppContants.APP_STATUS_CLOSE_LOSSCARD);
								for(SubaccountPersonal cardWallet:lsp){
									cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);
									cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);
									cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);
									cardWallet.setClsDate(null);
									cardWallet.setLossDate(null);
									spm.update(cardWallet);
								}
								//恢复应用
								List<AppOpenReg> la = aorm.queryAppOpenRegByRemark(vo.getCitizenCardNo(),AppContants.APP_STATUS_CLOSE_LOSSCARD);//该卡的之前挂失的应用
								for(AppOpenReg aor:la){
									if(AppContants.APP_STATUS_CLOSE.equals(aor.getAppStatus())){
										aor.setAppStatus(AppContants.APP_STATUS_OPEN);
										aor.setLastDate(now);
										aor.setRemark("恢复应用");
										aor.setLastOperator(activeUser.getUserNo().toString());
										aorm.update(aor);
									}
								}
								
								Calendar calendar = Calendar.getInstance();
								calendar.setTime(now);
								calendar.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
								BlackListRc blr = new BlackListRc();
								// blr.setAppType(appType);//置黑应用类型
								blr.setCitizenCardNo(vo.getCitizenCardNo());// 市民卡号
								blr.setRegisterType(BlackListContants.BL_CUR_STATUS_Relieve);// 登记类型																		// 生效日期
								blr.setRelieveDate(calendar.getTime());// 解除日期
								blr.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式 0-系统;
																							// 1-手工															// blr.setBlReason(blReason);//进黑名单原因
								blr.setBlReReason(BlackListContants.BL_RE_REASON_COUNTER_HANGING);// 解除黑名单原因
								// blr.setCriticalLevel(criticalLevel);//严重级别 0-9, 严重级别由低至高.
								blr.setBlSource(BlackListContants.BL_SOURCE_ALL);// 黑名单来源
								// blr.setReleaseSys(releaseSys);//下发系统
								// blr.setTransCode(transCode);//交易代码
								blr.setBusinessNo(bu.getBusinessNo());// 综合业务流水号
								// blr.setDoubtTrNo(doubtTrNo);/可疑交易流水号
								// blr.setssLockTrNo(lockTrNo);//锁卡交易流水号
								blr.setRemark("银行卡解挂");
								blr.setOperDate(now);
								blr.setOpNetworkNo(activeUser.getBranchNo());
								blr.setTellerNo(activeUser.getUserNo().toString());

								blrm.insert(blr);
								
								//黑名单解挂
								BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(vo.getCitizenCardNo());
								bb.setBlReReason(BlackListContants.BL_RE_REASON_COUNTER_HANGING);
								bb.setCurStatus(BlackListContants.BL_CUR_STATUS_Relieve);
								bb.setRelieveDate(calendar.getTime());
								bb.setLastBlRcDate(now);
								blgm.update(bb);
							}
						}
					}
				}
			}
			
		}
		
		cardm.batchUpdate(cardControls);
		//cdm.batchUpdate(cardDatas);
		cmm.batchInsert(cardManages);
		bm.batchInsert(businesses);
		cem.batchInsert(certs);
		
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateChangeSupplemrntStatus(List<String> list, ImportBankFileVo vv) throws ApplicationException {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		List<BankProvideChangeCardVo> bankProvideChangeCardVos=new ArrayList<>();
		List<String> newCardNos=new ArrayList<>();//新市民卡号
		List<String> oldCardNos=new ArrayList<>();//旧市民卡号
		List<Personal>personals=new ArrayList<>();//个人信息
		List<CardData> oldCardDatas=new ArrayList<>();//旧卡数据表
		List<CardControl> oldCardControls=new ArrayList<>();//旧卡控制表
		List<CardData> newCardDatas=new ArrayList<>();//新卡数据表
		List<CardControl> newCardControls=new ArrayList<>();//新卡控制表
		List<CardManage>cardManages=new ArrayList<>();//卡过程表
		List<Business>businesses=new ArrayList<>();//卡业务流水
		List<Cert>certs=new ArrayList<>();//凭证表
		//默认开通公交
		AppKind ak = akm.queryAppKindByAppFalg(AppContants.APP_FLAG_TRANSIT);
		//提取文件数据
		for(String string:list){
			BankProvideChangeCardVo bcvo=new BankProvideChangeCardVo();
			String [] array=StringUtils.splitPreserveAllTokens(string, "|");
			bcvo.setBussinessType(array[0]);
			bcvo.setNewBankCardNo(array[1]);	
			if(array[2]==""){
				CardData cardData=cdm.queryCardDataByBcNo(bcvo.getNewBankCardNo());
				if(cardData==null){
					throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "导入文件异常，卡号错误，无此人信息");
				}
				bcvo.setNewCitizenCardNo(cardData.getCitizenCardNo());
			}else{
				bcvo.setNewCitizenCardNo(array[2]);
			}
			bcvo.setOldBankCardNo(array[3]);
			if(array[4]==""){
				CardData cardData=cdm.queryCardDataByBcNo(bcvo.getOldBankCardNo());
				if(cardData==null){
					throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "导入文件异常，卡号错误，无此人信息");
				}
				bcvo.setOldCitizenCardNo(cardData.getCitizenCardNo());
			}else{
				bcvo.setOldCitizenCardNo(array[4]);
			}
			newCardNos.add(bcvo.getNewCitizenCardNo());
			oldCardNos.add(bcvo.getOldCitizenCardNo());
			bankProvideChangeCardVos.add(bcvo);
		}
		//验证文件卡号
		Set<String> set1=new HashSet<>(newCardNos);
		Set<String> set2=new HashSet<>(oldCardNos);
		if(set1.size()!=newCardNos.size()||set2.size()!=oldCardNos.size()){
			throw new ApplicationException(ErrorCode.BTC_HAS_ERROR,"SCX File Has Same");
		}
		oldCardControls=cardm.queryCardControlByCitizenNoList(oldCardNos);
		oldCardDatas=cdm.queryCardDataByCitizenCardNoList(oldCardNos);
		newCardControls=cardm.queryCardControlByCitizenNoList(newCardNos);
		newCardDatas=cdm.queryCardDataByCitizenCardNoList(newCardNos);
		personals=pm.getPersonalByCitizenCardNoList(oldCardNos);
		Date now =new Date();
		for(BankProvideChangeCardVo vo:bankProvideChangeCardVos){
			Personal p=null;
			for(CardData cd:oldCardDatas){
				//原卡卡数据
				if(cd.getCitizenCardNo().equals(vo.getOldCitizenCardNo())&&
						cd.getBcNo().equals(vo.getOldBankCardNo())){
					//获取个人信息
					for(Personal personal:personals){
						if(personal.getCustomerNo().equals(cd.getCustomerNo())){
							p=personal;
							break;
						}
					}
					for(CardControl cc:oldCardControls){
						//原卡卡控制
						if(cc.getCardDataId().intValue()==cd.getCardDataId().intValue()){
							
							//新增凭证
							Cert ce = new Cert();
							ce.setCertNo(SequenceNumberUtil.generatorCertNo());
							if(CardContants.STANDARD_CARD_BUSSINESS_SUP.equals(vo.getBussinessType()))
								ce.setCertType(CardContants.CARD_ISSUING_APPLY);
							else if(CardContants.STANDARD_CARD_BUSSINESS_CHA.equals(vo.getBussinessType())) 
								ce.setCertType(CardContants.CARD_CHANGE_APPLY);
							ce.setCardpCode(cd.getCardpCode());
							ce.setCardTypecode(cd.getCardTypecode());
							ce.setName(p.getCustomerName());
							ce.setPaperNo(p.getPaperNo());
							ce.setPaperType(p.getPaperType());
							ce.setBranch(activeUser.getBranchName());
							ce.setBranchNo(activeUser.getBranchNo());
							ce.setCardControlId(cc.getCardControlId());
							ce.setCrtDate(now);
							ce.setCrtOperator(activeUser.getUserNo().toString());
							ce.setLastOperator(activeUser.getUserNo().toString());
							ce.setLastDate(now);
							
							//新增业务流水
							Business bu = new Business();
							bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
							bu.setCustomerNo(cd.getCustomerNo());
							bu.setCardControlId(cc.getCardControlId());
							bu.setTellerNo(activeUser.getUserNo().toString());
							// bu.setTransDate(new Date());// 交易日期
							bu.setSeqStatus(CardContants.LSZT_NORMAL);
							bu.setRemark(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
							bu.setCertNo(ce.getCertNo());
							businesses.add(bu);
							ce.setBusinessNo(bu.getBusinessNo());
							certs.add(ce);
							//新增卡过程
							CardManage cardManage = new CardManage();
							cardManage.setProcessId(UUID.randomUUID().toString().replace("-", ""));
							cardManage.setApplyBranch(activeUser.getBranchName());
							cardManage.setApplyBranchNo(activeUser.getBranchNo());
							cardManage.setProcessCode(CardContants.CARD_PROC_WASTE_STORAGE);
							cardManage.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_WASTE_STORAGE));
							cardManage.setApplyTellerNo(activeUser.getUserNo().toString());
							cardManage.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
							cardManage.setCardpCode(cd.getCardpCode());							
							cardManage.setCardStatus(CardContants.CARD_STATE_CANCELLATION_NO_CARD);
							cardManage.setCardTypecode(cd.getCardTypecode());
							cardManage.setCustomerNo(cd.getCustomerNo());						
							cardManage.setRemark(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
							cardManage.setCardPosition(CardContants.CARD_POSITION_BANK);									
							cardManage.setApplyDate(now);
							cardManage.setCitizenCardNo(cd.getCitizenCardNo());
							cardManage.setBusinessNo(bu.getBusinessNo());
							cardManage.setCertNo(ce.getCertNo());
							cardManages.add(cardManage);
							
							//修改卡控制
							cc.setLogoutDate(now);// 注销日期
							cc.setLastDate(now);// 最后修改时间
							cc.setLastOperator(activeUser.getUserNo().toString());// 最后一次操作员
							cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_INNER);// 黑名单标识-拉黑
							cc.setCurrProcId(cardManage.getProcessId());
							cc.setIsRead("0");
							cc.setClaimStatus(CardContants.CLAIM_STATUS_CANCEL);
							//补卡业务
							if(vo.getBussinessType().equals(CardContants.STANDARD_CARD_BUSSINESS_SUP)){
								cc.setSupplementCardDate(now);
								cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);// 卡位置--市民
								cc.setCardStatus(CardContants.CARD_STATE_CANCELLATION_NO_CARD);// 卡状态--无卡注销
								cc.setLogoutReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
							}
							//换卡业务
							else if(vo.getBussinessType().equals(CardContants.STANDARD_CARD_BUSSINESS_CHA)){
								cc.setChangeCardDate(now);// 换卡日期
								cc.setCardPosition(CardContants.CARD_POSITION_BANK);// 卡位置--银行
								cc.setCardStatus(CardContants.CARD_STATE_CANCELLATION_HAS_CARD);// 卡状态--有卡注销
								cc.setLogoutReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
							}
							//应用和钱包在开通新卡账户时关闭
							//黑名单
							BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(cd.getCitizenCardNo());
							Calendar calendar = Calendar.getInstance();
							calendar.setTime(now);
							calendar.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
							if (bb == null) {
								bb = new BlackListGen();
								bb.setCitizenCardNo(cd.getCitizenCardNo());
								bb.setCityCode(CardContants.CITY_CODE);
								// bb.setAppType(appType);//置黑应用类型
								// bb.setChipsInno(chipsInno);//接触卡内号
								// bb.setChipsLessInno(chipsLessInno);//非接卡内号
								// bb.setChipsLessNo(chipsLessNo);//非接芯片号
								// bb.setChipsNo(chipsNo);//接触芯片号
								bb.setBlCount(1);// 进黑名单次数
								bb.setBlReCount(0);// 解除黑名单次数
								//bb.setBlReReason(blReReason);//解除黑名单原因
								// bb.setRelieveDate(relieveDate);//解除日期
								if(CardContants.STANDARD_CARD_BUSSINESS_SUP.equals(vo.getBussinessType()))
									bb.setBlReason(BlackListContants.BL_REASON_SUPPLEMENT_CARD_CANCELLATION );
								else if(vo.getBussinessType().equals(CardContants.STANDARD_CARD_BUSSINESS_CHA))
									bb.setBlReason(BlackListContants.BL_REASON_CHANGE_CARD_CANCELLATION );
								
								bb.setAvailDate(calendar.getTime());// 生效日期
								bb.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式
								bb.setReleaseSys(BlackListContants.BL_PUBLISHING_SYSTEM_LIST_ALl);// 发布系统列表
								bb.setCurStatus(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 当前状态
								bb.setLastBlRcDate(now);// 最后更新日期
								blgm.insert(bb);
							} else {
								bb.setBlCount(bb.getBlCount() + 1);
//								bb.setBlReReason(null);// 解除黑名单原因
//								bb.setRelieveDate(null);// 解除日期
								bb.setBlReason(CardContants.getBankBussinessTypeName(vo.getBussinessType()));					
								bb.setAvailDate(calendar.getTime());// 生效日期
								bb.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式
								bb.setReleaseSys(BlackListContants.BL_PUBLISHING_SYSTEM_LIST_ALl);// 发布系统列表
								bb.setCurStatus(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 当前状态
								bb.setLastBlRcDate(now);// 最后更新日期
								blgm.update(bb);
							}
							//黑名单记录表
							BlackListRc blr = new BlackListRc();
							// blr.setAppType(appType);//置黑应用类型
							blr.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
							blr.setRegisterType(BlackListContants.BL_CUR_STATUS_TAKE_EFFECT);// 登记类型																			// 2.解除
							blr.setAvailDate(calendar.getTime());// 生效日期
							// blr.setRelieveDate(relieveDate);//解除日期
							blr.setBlackMode(BlackListContants.BL_BLACK_MODE_SYSTEM);// 置黑方式 0-系统;																					// 1-手工
							if(CardContants.STANDARD_CARD_BUSSINESS_SUP.equals(vo.getBussinessType()))
								bb.setBlReason(BlackListContants.BL_REASON_SUPPLEMENT_CARD_CANCELLATION );
							else if(vo.getBussinessType().equals(CardContants.STANDARD_CARD_BUSSINESS_CHA))
								bb.setBlReason(BlackListContants.BL_REASON_CHANGE_CARD_CANCELLATION );
							// blr.setBlReReason(blReReason);//解除黑名单原因
							// blr.setCriticalLevel(criticalLevel);//严重级别 0-9, 严重级别由低至高.
							blr.setBlSource(BlackListContants.BL_SOURCE_ALL);// 黑名单来源
							// blr.setReleaseSys(releaseSys);//下发系统
							// blr.setTransCode(transCode);//交易代码
							blr.setBusinessNo(bu.getBusinessNo());// 综合业务流水号
							// blr.setDoubtTrNo(doubtTrNo);/可疑交易流水号
							// blr.setssLockTrNo(lockTrNo);//锁卡交易流水号
							blr.setRemark(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
							blr.setOperDate(now);
							blr.setOpNetworkNo(activeUser.getBranchNo());
							blr.setTellerNo(activeUser.getUserNo().toString());
							blrm.insert(blr);
								
						}
					}
				}
			}
			
			for(CardData cd:newCardDatas){
				//新卡卡数据
				if(cd.getCitizenCardNo().equals(vo.getNewCitizenCardNo())){
					cd.setCustomerNo(p.getCustomerNo());
					cd.setChcOriCitizenNo(vo.getOldCitizenCardNo());
					cd.setBcNo(vo.getNewBankCardNo());
					for(CardControl cc:newCardControls){	
						//新卡卡控制
						if(cc.getCardDataId().intValue()==cd.getCardDataId().intValue()){							
							//新增凭证
							Cert ce = new Cert();
							ce.setCertNo(SequenceNumberUtil.generatorCertNo());
							ce.setCertType(CardContants.CARD_ISSUING_CARD);
							ce.setCardpCode(cd.getCardpCode());
							ce.setCardTypecode(cd.getCardTypecode());
							ce.setName(p.getCustomerName());
							ce.setPaperNo(p.getPaperNo());
							ce.setPaperType(p.getPaperType());
							ce.setBranch(activeUser.getBranchName());
							ce.setBranchNo(activeUser.getBranchNo());
							ce.setCardControlId(cc.getCardControlId());
							ce.setCrtDate(now);
							ce.setCrtOperator(activeUser.getUserNo().toString());
							ce.setLastOperator(activeUser.getUserNo().toString());
							ce.setLastDate(now);
							
							
							//新增业务流水
							Business bu = new Business();
							bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
							bu.setCustomerNo(cd.getCustomerNo());
							bu.setCardControlId(cc.getCardControlId());
							bu.setTellerNo(activeUser.getUserNo().toString());
							// bu.setTransDate(new Date());// 交易日期
							bu.setSeqStatus(CardContants.LSZT_NORMAL);
							bu.setRemark(CardContants.getBankBussinessTypeName(vo.getBussinessType()));
							bu.setCertNo(ce.getCertNo());
							businesses.add(bu);
							ce.setBusinessNo(bu.getBusinessNo());
							certs.add(ce);
							
							//新增卡过程
							CardManage cardManage = new CardManage();
							cardManage.setProcessId(UUID.randomUUID().toString().replace("-", ""));
							cardManage.setApplyBranch(activeUser.getBranchName());
							cardManage.setApplyBranchNo(activeUser.getBranchNo());
							cardManage.setProcessCode(CardContants.CARD_PROC_RETRIEVE);
							cardManage.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
							cardManage.setApplyTellerNo(activeUser.getUserNo().toString());
							cardManage.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
							cardManage.setCardpCode(cd.getCardpCode());							
							cardManage.setCardStatus(CardContants.CARD_STATE_NORMAL);
							cardManage.setCardTypecode(cd.getCardTypecode());
							cardManage.setCustomerNo(cd.getCustomerNo());						
							cardManage.setRemark("银行补换卡发卡");
							cardManage.setCardPosition(CardContants.CARD_POSITION_BANK);									
							cardManage.setApplyDate(now);
							cardManage.setCitizenCardNo(cd.getCitizenCardNo());
							cardManage.setBusinessNo(bu.getBusinessNo());
							cardManage.setCertNo(ce.getCertNo());
							cardManages.add(cardManage);
							
							
							cc.setReleaseDate(now);// 发卡日期
							cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
							cc.setDmgFlag(CardContants.CARD_UNDAMAGED);
							cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
							cc.setCurrProcId(cardManage.getProcessId());
							cc.setLastDate(now);
							cc.setLastOperator(activeUser.getUserNo().toString());
							cc.setRemark("补/换  新卡发放");
							cc.setClaimStatus(CardContants.CLAIM_STATUS_GIVEN);
							cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
							
							//开通应用
							 //该卡开通的应用
							List<AppOpenReg> la = aorm.queryAppOpenRegByCitizenCardNo(vo.getOldCitizenCardNo(),AppContants.APP_STATUS_OPEN);
							if(la!=null&&la.size()>0){
								for(AppOpenReg aor:la){
									if(AppContants.APP_STATUS_OPEN.equals(aor.getAppStatus())){
										AppOpenReg aor2=new AppOpenReg();
										CopyBean.copyA2b(aor,aor2);
										aor.setStopDate(now);
										aor.setAppStatus(AppContants.APP_STATUS_CLOSE);
										aor.setLastDate(now);
										aor.setLastOperator(activeUser.getUserNo().toString());
										aor.setIsDeposit(AccountContants.IS_DEPOSIT_YES);
										aor.setRemark("银行补换卡 应用转移关闭");
										aorm.update(aor);//关闭
										
										aor2.setStopDate(null);
										aor2.setAppOpenregId(null);
										aor2.setAppStatus(AppContants.APP_STATUS_OPEN);
										aor2.setCitizenCardNo(cd.getCitizenCardNo());
										aor2.setOpenDate(now);
										aor2.setLastDate(now);
										if (ak.getValidMonthNum() != null) {
											aor2.setIsValid(AppContants.APP_ISVALID); // 月份计算
											aor2.setValidBegin(now);
											aor2.setValidEnd(CommonUtil.willDate(now, ak.getValidMonthNum()));

										} else {
											aor2.setIsValid(AppContants.APP_NOVALID); // 月份计算
										}
										aor2.setLastOperator(activeUser.getUserNo().toString());
										aor2.setRemark("银行补换卡 应用转移开通");
										aor2.setCrtOperator(activeUser.getUserNo().toString());
										aor2.setIsDeposit(AccountContants.IS_DEPOSIT_NO);
										aor2.setCrtDate(now);
										aorm.insert(aor2);//开通
										
										
									}
								}
							}
							//开钱包账户
							 //该卡开通的钱包
							List<SubaccountPersonal> lsp = spm.querySubaccountPersonalOpenByCitizenCardNo(vo.getOldCitizenCardNo(), AccountContants.ACCOUNT_STATUS_NORMAL);
							if(lsp!=null&&lsp.size()>0){
								for(SubaccountPersonal sp:lsp){
									if(sp.getAccountStatus().equals(AccountContants.ACCOUNT_STATUS_NORMAL)){
										SubaccountPersonal cardWallet=new SubaccountPersonal();
										CopyBean.copyA2b(sp, cardWallet);
										sp.setClsDate(now);
										sp.setClsTellerNo(activeUser.getUserNo().toString());
										sp.setAccountStatus(AccountContants.ACCOUNT_STATUS_CANCEL_ACCOUNT);
										sp.setFreezeAmount(sp.getTotalBalance());
										spm.update(sp);
										
										cardWallet.setAccoBranchNo(activeUser.getBranchNo());// 开户网点编号
										cardWallet.setAccoDate(now);// 开户日期
										cardWallet.setAccoTellerNo(activeUser.getUserNo().toString());// 开户柜员号
										//cardWallet.setAccountName(p.getCustomerName());// 户名
										//cardWallet.setAccountPw(AccountContants.CARD_WALLET_INT_PASSWORD);// 账户密码
										//cardWallet.setAccountSign(accountSign);//帐户标识
										cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);//帐号状态
										//cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_BANKBOOK);// 所属钱包类型id 01-电子存折 02-电子钱包
										//cardWallet.setAppFlag(akm.queryAppKindByAppFalg("3F01").getAppFlag());// 应用标识																		// 默认开通公交
										//cardWallet.setCardSeqNo(cappFlagardSeqNo);//卡片序列号
										cardWallet.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
										//cardWallet.setCityCode(CardContants.CITY_CODE);// 城市代码
										cardWallet.setClsDate(null);//销户日期
										cardWallet.setClsTellerNo(null);//销户柜员号
										cardWallet.setCrdBalance(new BigDecimal(0));// 卡面余额
										//cardWallet.setCrdNo(crdNo);//卡内号
										cardWallet.setCurrCount(0);// 当前计数器值
										//cardWallet.setCustomerNo(p.getCustomerNo());// 客户编号
										cardWallet.setErrorDegree((short) 0);// 输错次数
										cardWallet.setFreezeAmount(new BigDecimal(0));// 冻结金额
										cardWallet.setFreezeDate(null);//冻结日期
										cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);// 冻结标志
										//cardWallet.setInaccEndDate(inaccEndDate);//入账截止日期
										//cardWallet.setInaccEndStatus(inaccEndStatus);// 入账截止状态
										//cardWallet.setLastTransDate(lastTransDate);//最后交易日
										//cardWallet.setLastTransNo(lastTransNo);//最后交易流水号
										cardWallet.setLossDate(null);//挂失日期
										cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);// 挂失状态
										//cardWallet.setMainaccountNo(m.getMainaccountNo());// 主帐户号
										cardWallet.setMaxCount(0);// 最大计数器值
										//cardWallet.setOnlCurrCount(onlCurrCount);//联机交易计数器
										//cardWallet.setOnlTxnDt(onlTxnDt);//最后联机交易时间
										cardWallet.setPasswordStatus(null);// 密码标志
										cardWallet.setProductNumber(0);// 积数
										cardWallet.setRemark("银行补换卡开户");
										cardWallet.setSumJe(0);// 消费积分
										cardWallet.setTotalBalance(new BigDecimal(0));// 账面余额
										cardWallet.setTotalConsumeAmt(new BigDecimal(0));// 累计消费金额
										cardWallet.setTotalConsumeCnt(0);// 累计消费笔数
										cardWallet.setTotalExchangeAmt(new BigDecimal(0));// 累计圈存金额
										cardWallet.setTotalExchangeCnt(0);// 累计圈存笔数
										cardWallet.setTotalReloadAmt(new BigDecimal(0));// 累计充值金额
										cardWallet.setTotalReloadCnt(0);// 累计充值笔数
										cardWallet.setValidDate(null);// 有效期
										spm.insert(cardWallet);
									}
								}
							}
							
						}
					}
				}
			}
		}
		cdm.batchUpdate(newCardDatas);
		cardm.batchUpdate(oldCardControls);
		cardm.batchUpdate(newCardControls);
		cmm.batchInsert(cardManages);
		bm.batchInsert(businesses);
		cem.batchInsert(certs);
		
		
	}
	
	@Override
	public DwzPage<CardNoGeneratedVo> queryCardNoDetail(CardNoGeneratedVo cardNoGeneratedVo) {
		List<CardNoGeneratedVo> list=cngm.queryAllRecord(cardNoGeneratedVo);
		Iterator<CardNoGeneratedVo> iterator=list.iterator();
		while(iterator.hasNext()){
			CardNoGeneratedVo vo=iterator.next();
			if(!vo.getCardpCode().equals(CardContants.CARD_P_CODE_JS)&&!vo.getCardpCode().equals(CardContants.CARD_P_CODE_WF)){
				iterator.remove();
			}
		}
		DwzPage<CardNoGeneratedVo> dPage=new DwzPage<>(cardNoGeneratedVo.getCurrentPage(), cardNoGeneratedVo.getNumPerPage(), list.size());
		dPage.setList(list);
		return dPage;
	}

	@Override
	public List<CardNoUseDetail> queryAllRecord(CardNoUseDetail cardNoUseDetail) {
		List<CardNoUseDetail> list=cndm.queryAllRecord(cardNoUseDetail);
		return list;
	}

	private Date formatDate(String date) throws ParseException{
		date=new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(date));
		return new SimpleDateFormat("yyyy-MM-dd").parse(date);
	}


	
}
